home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / ld.sun4.broken / ld.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-09-26  |  175.4 KB  |  6,509 lines

  1. /* Linker `ld' for GNU
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Richard Stallman with some help from Eric Albert.
  19.    Set, indirect, and warning symbol features added by Randy Smith.  */
  20.  
  21. #include <ar.h>
  22. #include <stdio.h>
  23. #include <sys/types.h>
  24. #include <sys/stat.h>
  25. #include <sys/file.h>
  26. #ifndef USG
  27. #include <sys/time.h>
  28. #include <sys/resource.h>
  29. #endif
  30. #ifndef sony_news
  31. #include <fcntl.h>
  32. #endif
  33.  
  34. #define TARGET_SUN2             2
  35. #define TARGET_SUN3             3
  36. #define TARGET_SUN4             4
  37. #define TARGET_ALTOS            5
  38. #define TARGET_I386             6   
  39. #define TARGET_HPUX             7
  40. #define TARGET_SONY_NEWS        8
  41. #define TARGET_SEQUENT          9
  42. #define TARGET_VAX              10
  43.  
  44. /*
  45.  * If `TARGET_MACHINE' was not defined on the compiler command line,
  46.  * then set it equal to the host machine.
  47.  */
  48. #ifndef TARGET_MACHINE
  49. #if defined(sun) && defined(sparc)
  50. #define TARGET_MACHINE  TARGET_SUN4
  51. #endif
  52. #if defined(sun) && (defined(m68020) || defined(mc68020))
  53. #define TARGET_MACHINE  TARGET_SUN3
  54. #endif
  55. #if defined(sun) && (defined(m68010) || defined(mc68010))
  56. #define TARGET_MACHINE  TARGET_SUN2
  57. #endif
  58. #if defined(ALTOS)
  59. #define TARGET_MACHINE  TARGET_ALTOS
  60. #endif
  61. #if defined(hpux)
  62. #define TARGET_MACHINE  TARGET_HPUX
  63. #endif
  64. #if defined(is386)
  65. #define TARGET_MACHINE  TARGET_I386
  66. #endif
  67. #if defined(sony_news)
  68. #define TARGET_MACHINE  TARGET_SONY_NEWS
  69. #endif
  70. #if defined(sequent)
  71. #define TARGET_MACHINE  TARGET_SEQUENT
  72. #endif
  73. #if defined(is68k) && !defined(TARGET_MACHINE)
  74. #define TARGET_MACHINE  TARGET_68K
  75. #endif
  76. #endif
  77.  
  78. #ifndef TARGET_MACHINE
  79.  CANNOT COMPILE, NO TARGET MACHINE SPECIFIED
  80. #endif
  81.  
  82. #ifndef BIG_ENDIAN
  83. #define BIG_ENDIAN      4321
  84. #endif
  85. #ifndef LITTLE_ENDIAN
  86. #define LITTLE_ENDIAN   1234
  87. #endif
  88. #ifndef PDP_ENDIAN
  89. /* I think it is unlikely that anybody will try to cross compile
  90.  * to or from a pdp, so only big-endian and little-endian are supported. */
  91. #define PDP_ENDIAN   3412
  92. #endif
  93.  
  94. #if TARGET_MACHINE==TARGET_SUN4      || \
  95.  TARGET_MACHINE==TARGET_SUN3         || \
  96.  TARGET_MACHINE==TARGET_SUN2         || \
  97.  TARGET_MACHINE==TARGET_ALTOS        || \
  98.  TARGET_MACHINE==TARGET_HPUX         || \
  99.  TARGET_MACHINE==TARGET_SONY_NEWS    || \
  100.  TARGET_MACHINE==TARGET_68K
  101. #define TARGET_BYTE_ORDER       BIG_ENDIAN
  102. #endif
  103.  
  104. #if TARGET_MACHINE==TARGET_VAX          || \
  105.  TARGET_MACHINE==TARGET_I386         || \
  106.  TARGET_MACHINE==TARGET_SEQUENT
  107. #define TARGET_BYTE_ORDER       LITTLE_ENDIAN
  108. #endif
  109.  
  110. #if TARGET_MACHINE==TARGET_SUN3
  111. #define TARGET_PAGE_SIZE    0x2000
  112. #endif
  113.  
  114. #if defined(sparc)   || \
  115.  defined(m68000)     || \
  116.  defined(mc68000)    || \
  117.  defined(m68010)     || \
  118.  defined(mc68010)    || \
  119.  defined(m68020)     || \
  120.  defined(mc68020)    || \
  121.  defined(is68k)      || \
  122.  defined(hpux)       || \
  123.  defined(sony_news)
  124. #define HOST_BYTE_ORDER     BIG_ENDIAN
  125. #endif
  126.  
  127. #if defined(vax)     || \
  128.  defined(is386)      || \
  129.  defined(ds3100)     || \
  130.  defined(sequent)
  131. #define HOST_BYTE_ORDER     LITTLE_ENDIAN
  132. #endif
  133.  
  134. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  135. static void fix_byte_order();
  136. static void fix_exec_header_byte_order();
  137. static void fix_symbol_byte_order();
  138. static void target_to_host_reloc_byte_order();
  139. static void host_to_target_reloc_byte_order();
  140. static void fix_symbol_root_byte_order();
  141. #endif
  142.  
  143. #if !defined(A_OUT) && !defined(MACH_O)
  144. #define A_OUT
  145. #endif
  146.  
  147. #ifdef A_OUT
  148. #ifdef COFF_ENCAPSULATE
  149. #include "a.out.encap.h"
  150. #else
  151. #ifdef sprite
  152. #if TARGET_MACHINE==TARGET_SUN4
  153. #include <sun4.md/a.out.h>
  154. #elif TARGET_MACHINE==TARGET_SUN3
  155. #include <sun3.md/a.out.h>
  156. #elif TARGET_MACHINE==TARGET_SEQUENT
  157. #include <symm.md/a.out.h>
  158. #else
  159.  no a.out.h specified
  160. #endif
  161. #else
  162. #include <a.out.h>
  163. #endif
  164. #endif
  165. #endif
  166.  
  167. #ifdef MACH_O
  168. #ifndef A_OUT
  169. #include <nlist.h>
  170. #include <reloc.h>
  171. #endif
  172. #ifndef N_TEXT
  173. #define N_TEXT 0x04
  174. #define N_DATA 0x06
  175. #define N_BSS 0x08
  176. #endif
  177. #include <sys/loader.h>
  178. #endif
  179.  
  180. #ifdef sprite
  181. #undef NEW_SEG_SIZE
  182. #if TARGET_MACHINE==TARGET_SUN4
  183. #define NEW_SEG_SIZE    0x40000
  184. #endif
  185. #if TARGET_MACHINE==TARGET_SUN3
  186. #define NEW_SEG_SIZE    0x20000
  187. #endif
  188. #endif  /* sprite */
  189.  
  190. #ifndef N_SET_MAGIC
  191. #define N_SET_MAGIC(exec, val)  ((exec).a_magic = val)
  192. #endif
  193.  
  194. /* If compiled with GNU C, use the built-in alloca */
  195. #ifdef __GNUC__
  196. # define alloca __builtin_alloca
  197. #else
  198. # if defined(sun) && defined(sparc)
  199. #  include "alloca.h"
  200. # else
  201. char *alloca ();
  202. # endif
  203. #endif
  204.  
  205. #include "getopt.h"
  206.  
  207. /* Always use the GNU version of debugging symbol type codes, if possible.  */
  208.  
  209. #include "stab.h"
  210. #define CORE_ADDR unsigned long    /* For symseg.h */
  211. #include "symseg.h"
  212.  
  213. #ifdef USG
  214. #include <string.h>
  215. #else
  216. #include <strings.h>
  217. #endif
  218.  
  219. /* Determine whether we should attempt to handle (minimally)
  220.    N_BINCL and N_EINCL.  */
  221.  
  222. #if defined (__GNU_STAB__) || defined (N_BINCL)
  223. #define HAVE_SUN_STABS
  224. #endif
  225.  
  226. #define min(a,b) ((a) < (b) ? (a) : (b))
  227.  
  228. /* Macro to control the number of undefined references printed */
  229. #define MAX_UREFS_PRINTED    10
  230.  
  231. /* Size of a page; obtained from the operating system.  */
  232.  
  233. int page_size;
  234.  
  235. /* Name this program was invoked by.  */
  236.  
  237. char *progname;
  238.  
  239. /* System dependencies */
  240.  
  241. /* Define this if names etext, edata and end should not start with `_'.  */
  242. /* #define nounderscore 1 */
  243.  
  244. /* Define NON_NATIVE if using BSD or pseudo-BSD file format on a system
  245.    whose native format is different.  */
  246. /* #define NON_NATIVE */
  247.  
  248. /* Define this to specify the default executable format.  */
  249.  
  250. #if TARGET_MACHINE==TARGET_HPUX
  251. #define DEFAULT_OUTPUT_STYLE OUTPUT_READONLY_TEXT
  252. #endif
  253.  
  254. /* Ordinary 4.3bsd lacks these macros in a.out.h.  */
  255.  
  256. #ifndef N_TXTADDR
  257. #if TARGET_MACHINE==TARGET_VAX || TARGET_MACHINE==TARGET_SONY_NEWS
  258. #define N_TXTADDR(X) 0
  259. #endif
  260. #if TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  261. #define N_TXTADDR(x)  (sizeof (struct exec))
  262. #endif
  263. #if TARGET_MACHINE==TARGET_SEQUENT
  264. #define    N_TXTADDR(x) (N_ADDRADJ(x))
  265. #endif
  266. #ifdef TARGET_MACHINE==TARGET_NeXT
  267. #define N_TXTADDR(X) ((X).a_magic == ZMAGIC ? page_size : 0)
  268. #endif
  269. #endif
  270.  
  271. #ifndef N_DATADDR
  272. #if TARGET_MACHINE==TARGET_VAX || TARGET_MACHINE==TARGET_SONY_NEWS
  273. #define N_DATADDR(x) \
  274.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  275.     : (page_size+((N_TXTADDR(x)+(x).a_text-1) & ~(page_size-1))))
  276. #endif
  277. #if TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  278. #define SEGMENT_SIZE 0x20000
  279. #define N_DATADDR(x) \
  280.     (((x).a_magic==Omagic)? (N_TXTADDR(x)+(x).a_text) \
  281.      : (SEGMENT_SIZE + ((N_TXTADDR(x)+(x).a_text-1) & ~(SEGMENT_SIZE-1))))
  282. #endif
  283. #if TARGET_MACHINE==TARGET_SEQUENT
  284. #define N_DATADDR(x) \
  285.     (((x).a_magic==OMAGIC)? (N_TXTADDR(x)+(x).a_text) \
  286.     : (page_size+(((x).a_text-1) & ~(page_size-1))))
  287. #endif
  288. #ifdef TARGET_MACHINE==TARGET_MACHINE_NeXT
  289. #define N_DATADDR(X) \
  290.     (((X).a_magic==ZMAGIC)?(N_TXTADDR(X)+(X).a_text+0xFFFF)&~0xFFFF \
  291.      :N_TXTADDR(X)+(X).a_text)
  292. #endif
  293. #endif
  294.  
  295. /* The "address" of the data segment in a relocatable file.
  296.    The text address of a relocatable file is always
  297.    considered to be zero (instead of the value of N_TXTADDR, which
  298.    is what the address is in an executable), so we need to subtract
  299.    N_TXTADDR from N_DATADDR to get the "address" for the input file.  */
  300. #define DATA_ADDR_DOT_O(hdr) (N_DATADDR(hdr) - N_TXTADDR(hdr))
  301.  
  302. /* Define how to initialize system-dependent header fields.  */
  303. #if TARGET_MACHINE==TARGET_SUN4
  304. #define INITIALIZE_HEADER \
  305.   {outheader.a_machtype = M_SPARC; outheader.a_toolversion = 1;}
  306. #endif /* sparc.  */
  307. #if TARGET_MACHINE==TARGET_SUN2 || TARGET_MACHINE==TARGET_SUN3
  308. /* Set the machine type according to the machine type of the .o files.
  309.    If they are all sun2 (68010), then the type of the executable is sun2.
  310.    If any is sun3 (68020), then the type of the executable is sun3.
  311.    This is consistent with the Sun loader and more useful than having
  312.    it depend on which machine you are on when you run ld.  */
  313. static int sun_machtype = M_68010;
  314. #define INITIALIZE_HEADER outheader.a_machtype = sun_machtype
  315. #define READ_HEADER_HOOK(machtype) \
  316.   if (machtype == M_68020)           \
  317.     {                     \
  318.       sun_machtype = M_68020;         \
  319.     }
  320. #endif
  321.  
  322. #if TARGET_MACHINE==TARGET_ALTOS
  323. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_68020)
  324. #endif
  325. #if TARGET_MACHINE==TARGET_68K
  326. #ifdef M_68020
  327. /* ISI rel 4.0D doesn't use it, and rel 3.05 doesn't have an
  328.    a_machtype field and so won't recognize the magic number.  To keep
  329.    binary compatibility for now, just ignore it */
  330. #define INITIALIZE_HEADER outheader.a_machtype = 0;
  331. #endif
  332. #endif
  333. #if TARGET_MACHINE==TARGET_HPUX
  334. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, HP9000S200_ID)
  335. #endif
  336. #if TARGET_MACHINE==TARGET_I386
  337. #define INITIALIZE_HEADER N_SET_MACHTYPE (outheader, M_386)
  338. #endif
  339. #if TARGET_MACHINE==TARGET_HP300
  340. #define INITIALIZE_HEADER outheader.a_mid = MID_HP300
  341. #endif
  342. #if TARGET_MACHINE==TARGET_PYR
  343. #define INITIALIZE_HEADER outheader.a_machid = PYR90X
  344. #endif /* Pyramid.  */
  345.  
  346. #if TARGET_MACHINE==TARGET_68K
  347. /* This enables code to take care of an ugly hack in the ISI OS.
  348.    If a symbol beings with _$, then the object file is included only
  349.    if the rest of the symbol name has been referenced. */
  350. #define DOLLAR_KLUDGE
  351. #endif
  352. #if TARGET==TARGET_SEQUENT
  353. /* This is all stuff needed to make standalone binaries */
  354. static struct gdtbl gdt_filler = {
  355.     { 0x0000FFFF, 0x00CF9A00 },    /* code entry */
  356.     { 0x0000FFFF, 0x00CF9200 },    /* data entry */
  357.     { 0x00180017, 0x00000000 },    /* 6 byte descriptor */
  358. };
  359.  
  360. static char instr[] = {
  361.     0x67, 0x66, 0x0f, 0x01, 0x15, 0x30, 0x00, 0x00, 0x00,
  362.     0x0f, 0x20, 0xc3,
  363.     0x80, 0xcb, 0x01,
  364.     0x0f, 0x22, 0xc3,
  365.     0xea, 0x5b, 0x00, 0x08, 0x00,
  366.     0xbb, 0x10, 0x00, 0x00, 0x00,
  367.     0x8e, 0xdb,
  368.     0x8e, 0xd3,
  369.     0x8e, 0xc3,
  370.     0xff, 0x25, 0x6c, 0x00, 0x00, 0x00,
  371.     0x00, 0x00, 0x00, 0x00, };
  372. #endif   
  373.  
  374. /* Values for 3rd argument to lseek().  */
  375. #ifndef L_SET
  376. #define L_SET 0
  377. #endif
  378. /* This is called L_INCR in BSD, but SEEK_CUR in POSIX.  */
  379. #ifndef SEEK_CUR
  380. #define SEEK_CUR 1
  381. #endif
  382.  
  383. /*
  384.  * Ok.  Following are the relocation information macros.  If your
  385.  * system cannot use the default set (below), you must define all of these:
  386.  
  387.  *   relocation_info: This must be typedef'd (or #define'd) to the type
  388.  * of structure that is stored in the relocation info section of your
  389.  * a.out files.  Often this is defined in the a.out.h for your system.
  390.  *
  391.  *   RELOC_ADDRESS (rval): Offset into the current section of the
  392.  * <whatever> to be relocated.  *Must be an lvalue*.
  393.  *
  394.  *   RELOC_EXTERN_P (rval):  Is this relocation entry based on an
  395.  * external symbol (1), or was it fully resolved upon entering the
  396.  * loader (0) in which case some combination of the value in memory
  397.  * (if RELOC_MEMORY_ADD_P) and the extra (if RELOC_ADD_EXTRA) contains
  398.  * what the value of the relocation actually was.  *Must be an lvalue*.
  399.  *
  400.  *   RELOC_TYPE (rval): For a non-external relocation, this is the
  401.  * segment to relocate for.  *Must be an lvalue.*
  402.  *
  403.  *   RELOC_SYMBOL (rval): For an external relocation, this is the
  404.  * index of its symbol in the symbol table.  *Must be an lvalue*.
  405.  *
  406.  *   RELOC_MEMORY_ADD_P (rval): This should be 1 if the final
  407.  * relocation value output here should be added to memory; 0, if the
  408.  * section of memory described should simply be set to the relocation
  409.  * value.
  410.  *
  411.  *   RELOC_MEMORY_ADD_P (rval): If this is nonzero, the value previously
  412.  * present in the memory location to be relocated is *added*
  413.  * to the relocation value, to produce the final result.
  414.  * Otherwise, the relocation value is stored in the memory location
  415.  * and the value previously found there is ignored.
  416.  * By default, this is always 1.
  417.  *
  418.  *   RELOC_MEMORY_SUB_P (rval): If this is nonzero, the value previously
  419.  * present in the memory location to be relocated is *subtracted*
  420.  * from the relocation value, to produce the final result.
  421.  * By default, this is always 0.
  422.  *
  423.  *   RELOC_ADD_EXTRA (rval): (Optional) This macro, if defined, gives
  424.  * an extra value to be added to the relocation value based on the
  425.  * individual relocation entry.  *Must be an lvalue if defined*.
  426.  *
  427.  *   RELOC_PCREL_P (rval): True if the relocation value described is
  428.  * pc relative.
  429.  *
  430.  *   RELOC_VALUE_RIGHTSHIFT (rval): Number of bits right to shift the
  431.  * final relocation value before putting it where it belongs.
  432.  *
  433.  *   RELOC_TARGET_SIZE (rval): log to the base 2 of the number of
  434.  * bytes of size this relocation entry describes; 1 byte == 0; 2 bytes
  435.  * == 1; 4 bytes == 2, and etc.  This is somewhat redundant (we could
  436.  * do everything in terms of the bit operators below), but having this
  437.  * macro could end up producing better code on machines without fancy
  438.  * bit twiddling.  Also, it's easier to understand/code big/little
  439.  * endian distinctions with this macro.
  440.  *
  441.  *   RELOC_TARGET_BITPOS (rval): The starting bit position within the
  442.  * object described in RELOC_TARGET_SIZE in which the relocation value
  443.  * will go.
  444.  *
  445.  *   RELOC_TARGET_BITSIZE (rval): How many bits are to be replaced
  446.  * with the bits of the relocation value.  It may be assumed by the
  447.  * code that the relocation value will fit into this many bits.  This
  448.  * may be larger than RELOC_TARGET_SIZE if such be useful.
  449.  *
  450.  *
  451.  *        Things I haven't implemented
  452.  *        ----------------------------
  453.  *
  454.  *    Values for RELOC_TARGET_SIZE other than 0, 1, or 2.
  455.  *
  456.  *    Pc relative relocation for External references.
  457.  *
  458.  *
  459.  */
  460.  
  461. #if TARGET_MACHINE==TARGET_SUN4
  462. /* Sparc (Sun 4) macros */
  463. #undef relocation_info
  464. #define relocation_info                    reloc_info_sparc
  465. #define RELOC_ADDRESS(r)        ((r)->r_address)
  466. #define RELOC_EXTERN_P(r)               ((r)->r_extern)
  467. #define RELOC_TYPE(r)                   ((r)->r_index)
  468. #define RELOC_SYMBOL(r)                 ((r)->r_index)
  469. #define RELOC_MEMORY_SUB_P(r)        0
  470. #define RELOC_MEMORY_ADD_P(r)           0
  471. #define RELOC_ADD_EXTRA(r)              ((r)->r_addend)
  472. #define RELOC_PCREL_P(r)                \
  473.  ((int) (r)->r_type >= (int) RELOC_DISP8 && \
  474.   (int) (r)->r_type <= (int) RELOC_WDISP22)
  475. #define RELOC_VALUE_RIGHTSHIFT(r) \
  476.     (reloc_target_rightshift[(int) (r)->r_type])
  477. #define RELOC_TARGET_SIZE(r)            (reloc_target_size[(int) (r)->r_type])
  478. #define RELOC_TARGET_BITPOS(r)          0
  479. #define RELOC_TARGET_BITSIZE(r) \
  480.     (reloc_target_bitsize[(int) (r)->r_type])
  481.  
  482. /* Note that these are very dependent on the order of the enums in
  483.    enum reloc_type (in a.out.h); if they change the following must be
  484.    changed */
  485. /* Also note that the last few may be incorrect; I have no information */
  486. static int reloc_target_rightshift[] = {
  487.   0, 0, 0, 0, 0, 0, 2, 2, 10, 0, 0, 0, 0, 0, 0,
  488. };
  489. static int reloc_target_size[] = {
  490.   0, 1, 2, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  491. };
  492. static int reloc_target_bitsize[] = {
  493.   8, 16, 32, 8, 16, 32, 30, 22, 22, 22, 13, 10, 32, 32, 16,
  494. };
  495.  
  496. #define    MAX_ALIGNMENT    (sizeof (double))
  497.   /* The pagesize on an old sun4 is 0x2000, on sparcStation it is 0x1000.
  498.      If you want to use the same binaries on both, then you need to use
  499.      the larger pagesize. */
  500. #define TARGET_PAGE_SIZE    0x2000
  501. #endif
  502.  
  503. #if TARGET_MACHINE==TARGET_SEQUENT
  504. #define RELOC_ADDRESS(r)        ((r)->r_address)
  505. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  506. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  507. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  508. #define RELOC_MEMORY_SUB_P(r)    ((r)->r_bsr)
  509. #define RELOC_MEMORY_ADD_P(r)    1
  510. #undef RELOC_ADD_EXTRA
  511. #define RELOC_PCREL_P(r)        ((r)->r_pcrel || (r)->r_bsr)
  512. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  513. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  514. #define RELOC_TARGET_BITPOS(r)    0
  515. #define RELOC_TARGET_BITSIZE(r)    32
  516. #define TARGET_PAGE_SIZE    0x1000
  517. #endif
  518.  
  519. /* Default macros */
  520. #ifndef RELOC_ADDRESS
  521. #define RELOC_ADDRESS(r)        ((r)->r_address)
  522. #define RELOC_EXTERN_P(r)        ((r)->r_extern)
  523. #define RELOC_TYPE(r)        ((r)->r_symbolnum)
  524. #define RELOC_SYMBOL(r)        ((r)->r_symbolnum)
  525. #define RELOC_MEMORY_SUB_P(r)    0
  526. #define RELOC_MEMORY_ADD_P(r)    1
  527. #undef RELOC_ADD_EXTRA
  528. #define RELOC_PCREL_P(r)        ((r)->r_pcrel)
  529. #define RELOC_VALUE_RIGHTSHIFT(r)    0
  530. #define RELOC_TARGET_SIZE(r)        ((r)->r_length)
  531. #define RELOC_TARGET_BITPOS(r)    0
  532. #define RELOC_TARGET_BITSIZE(r)    32
  533. #endif
  534.  
  535. #ifndef MAX_ALIGNMENT
  536. #define    MAX_ALIGNMENT    (sizeof (int))
  537. #endif
  538.  
  539. #ifdef nounderscore
  540. #define LPREFIX '.'
  541. #else
  542. #define LPREFIX 'L'
  543. #endif
  544.  
  545.  
  546. /* Special global symbol types understood by GNU LD.  */
  547.  
  548. /* The following type indicates the definition of a symbol as being
  549.    an indirect reference to another symbol.  The other symbol
  550.    appears as an undefined reference, immediately following this symbol.
  551.  
  552.    Indirection is asymmetrical.  The other symbol's value will be used
  553.    to satisfy requests for the indirect symbol, but not vice versa.
  554.    If the other symbol does not have a definition, libraries will
  555.    be searched to find a definition.
  556.  
  557.    So, for example, the following two lines placed in an assembler
  558.    input file would result in an object file which would direct gnu ld
  559.    to resolve all references to symbol "foo" as references to symbol
  560.    "bar".
  561.  
  562.     .stabs "_foo",11,0,0,0
  563.     .stabs "_bar",1,0,0,0
  564.  
  565.    Note that (11 == (N_INDR | N_EXT)) and (1 == (N_UNDF | N_EXT)).  */
  566.  
  567. #ifndef N_INDR
  568. #define N_INDR 0xa
  569. #endif
  570.  
  571. /* The following symbols refer to set elements.  These are expected
  572.    only in input to the loader; they should not appear in loader
  573.    output (unless relocatable output is requested).  To be recognized
  574.    by the loader, the input symbols must have their N_EXT bit set.
  575.    All the N_SET[ATDB] symbols with the same name form one set.  The
  576.    loader collects all of these elements at load time and outputs a
  577.    vector for each name.
  578.    Space (an array of 32 bit words) is allocated for the set in the
  579.    data section, and the n_value field of each set element value is
  580.    stored into one word of the array.
  581.    The first word of the array is the length of the set (number of
  582.    elements).  The last word of the vector is set to zero for possible
  583.    use by incremental loaders.  The array is ordered by the linkage
  584.    order; the first symbols which the linker encounters will be first
  585.    in the array.
  586.  
  587.    In C syntax this looks like:
  588.  
  589.     struct set_vector {
  590.       unsigned int length;
  591.       unsigned int vector[length];
  592.       unsigned int always_zero;
  593.     };
  594.  
  595.    Before being placed into the array, each element is relocated
  596.    according to its type.  This allows the loader to create an array
  597.    of pointers to objects automatically.  N_SETA type symbols will not
  598.    be relocated.
  599.  
  600.    The address of the set is made into an N_SETV symbol
  601.    whose name is the same as the name of the set.
  602.    This symbol acts like a N_DATA global symbol
  603.    in that it can satisfy undefined external references.
  604.  
  605.    For the purposes of determining whether or not to load in a library
  606.    file, set element definitions are not considered "real
  607.    definitions"; they will not cause the loading of a library
  608.    member.
  609.  
  610.    If relocatable output is requested, none of this processing is
  611.    done.  The symbols are simply relocated and passed through to the
  612.    output file.
  613.  
  614.    So, for example, the following three lines of assembler code
  615.    (whether in one file or scattered between several different ones)
  616.    will produce a three element vector (total length is five words;
  617.    see above), referenced by the symbol "_xyzzy", which will have the
  618.    addresses of the routines _init1, _init2, and _init3.
  619.  
  620.    *NOTE*: If symbolic addresses are used in the n_value field of the
  621.    defining .stabs, those symbols must be defined in the same file as
  622.    that containing the .stabs.
  623.  
  624.     .stabs "_xyzzy",23,0,0,_init1
  625.     .stabs "_xyzzy",23,0,0,_init2
  626.     .stabs "_xyzzy",23,0,0,_init3
  627.  
  628.    Note that (23 == (N_SETT | N_EXT)).  */
  629.  
  630. #ifndef N_SETA
  631. #define    N_SETA    0x14        /* Absolute set element symbol */
  632. #endif                /* This is input to LD, in a .o file.  */
  633.  
  634. #ifndef N_SETT
  635. #define    N_SETT    0x16        /* Text set element symbol */
  636. #endif                /* This is input to LD, in a .o file.  */
  637.  
  638. #ifndef N_SETD
  639. #define    N_SETD    0x18        /* Data set element symbol */
  640. #endif                /* This is input to LD, in a .o file.  */
  641.  
  642. #ifndef N_SETB
  643. #define    N_SETB    0x1A        /* Bss set element symbol */
  644. #endif                /* This is input to LD, in a .o file.  */
  645.  
  646. /* Macros dealing with the set element symbols defined in a.out.h */
  647. #define    SET_ELEMENT_P(x)    ((x)>=N_SETA&&(x)<=(N_SETB|N_EXT))
  648. #define TYPE_OF_SET_ELEMENT(x)    ((x)-N_SETA+N_ABS)
  649.  
  650. #ifndef N_SETV
  651. #define N_SETV    0x1C        /* Pointer to set vector in data area.  */
  652. #endif                /* This is output from LD.  */
  653.  
  654. /* If a this type of symbol is encountered, its name is a warning
  655.    message to print each time the symbol referenced by the next symbol
  656.    table entry is referenced.
  657.  
  658.    This feature may be used to allow backwards compatibility with
  659.    certain functions (eg. gets) but to discourage programmers from
  660.    their use.
  661.  
  662.    So if, for example, you wanted to have ld print a warning whenever
  663.    the function "gets" was used in their C program, you would add the
  664.    following to the assembler file in which gets is defined:
  665.  
  666.     .stabs "Obsolete function \"gets\" referenced",30,0,0,0
  667.     .stabs "_gets",1,0,0,0
  668.  
  669.    These .stabs do not necessarily have to be in the same file as the
  670.    gets function, they simply must exist somewhere in the compilation.  */
  671.  
  672. #ifndef N_WARNING
  673. #define N_WARNING 0x1E        /* Warning message to print if symbol
  674.                    included */
  675. #endif                /* This is input to ld */
  676.  
  677. #ifndef __GNU_STAB__
  678.  
  679. /* Line number for the data section.  This is to be used to describe
  680.    the source location of a variable declaration.  */
  681. #ifndef N_DSLINE
  682. #define N_DSLINE (N_SLINE+N_DATA-N_TEXT)
  683. #endif
  684.  
  685. /* Line number for the bss section.  This is to be used to describe
  686.    the source location of a variable declaration.  */
  687. #ifndef N_BSLINE
  688. #define N_BSLINE (N_SLINE+N_BSS-N_TEXT)
  689. #endif
  690.  
  691. #endif /* not __GNU_STAB__ */
  692.  
  693. /* Symbol table */
  694.  
  695. /* Global symbol data is recorded in these structures,
  696.    one for each global symbol.
  697.    They are found via hashing in 'symtab', which points to a vector of buckets.
  698.    Each bucket is a chain of these structures through the link field.  */
  699.  
  700. typedef
  701.   struct glosym
  702.     {
  703.       /* Pointer to next symbol in this symbol's hash bucket.  */
  704.       struct glosym *link;
  705.       /* Name of this symbol.  */
  706.       char *name;
  707.       /* Value of this symbol as a global symbol.  */
  708.       long value;
  709.       /* Chain of external 'nlist's in files for this symbol, both defs
  710.      and refs.  */
  711.       struct nlist *refs;
  712.       /* Any warning message that might be associated with this symbol
  713.          from an N_WARNING symbol encountered. */
  714.       char *warning;
  715.       /* Nonzero means definitions of this symbol as common have been seen,
  716.      and the value here is the largest size specified by any of them.  */
  717.       int max_common_size;
  718.       /* For OUTPUT_RELOCATABLE, records the index of this global sym in the
  719.      symbol table to be written, with the first global sym given index 0.*/
  720.       int def_count;
  721.       /* Nonzero means a definition of this global symbol is known to exist.
  722.      Library members should not be loaded on its account.  */
  723.       char defined;
  724.       /* Nonzero means a reference to this global symbol has been seen
  725.      in a file that is surely being loaded.
  726.      A value higher than 1 is the n_type code for the symbol's
  727.      definition.  */
  728.       char referenced;
  729.       /* A count of the number of undefined references printed for a
  730.      specific symbol.  If a symbol is unresolved at the end of
  731.      digest_symbols (and the loading run is supposed to produce
  732.      relocatable output) do_file_warnings keeps track of how many
  733.      unresolved reference error messages have been printed for
  734.      each symbol here.  When the number hits MAX_UREFS_PRINTED,
  735.      messages stop. */
  736.       unsigned char undef_refs;
  737.       /* 1 means that this symbol has multiple definitions.  2 means
  738.          that it has multiple definitions, and some of them are set
  739.      elements, one of which has been printed out already.  */
  740.       unsigned char multiply_defined;
  741.       /* Nonzero means print a message at all refs or defs of this symbol */
  742.       char trace;
  743.     }
  744.   symbol;
  745.  
  746. /* Demangler for C++.  */
  747. extern char *cplus_demangle ();
  748.  
  749. /* Demangler function to use.  We unconditionally enable the C++ demangler
  750.    because we assume any name it successfully demangles was probably produced
  751.    by the C++ compiler.  Enabling it only if -lg++ was specified seems too
  752.    much of a kludge.  */
  753. char *(*demangler)() = cplus_demangle;
  754.  
  755. /* Number of buckets in symbol hash table */
  756. #define    TABSIZE    1009
  757.  
  758. /* The symbol hash table: a vector of TABSIZE pointers to struct glosym. */
  759. symbol *symtab[TABSIZE];
  760.  
  761. /* Number of symbols in symbol hash table. */
  762. int num_hash_tab_syms = 0;
  763.  
  764. /* Count the number of nlist entries that are for local symbols.
  765.    This count and the three following counts
  766.    are incremented as as symbols are entered in the symbol table.  */
  767. int local_sym_count;
  768.  
  769. /* Count number of nlist entries that are for local symbols
  770.    whose names don't start with L. */
  771. int non_L_local_sym_count;
  772.  
  773. /* Count the number of nlist entries for debugger info.  */
  774. int debugger_sym_count;
  775.  
  776. /* Count the number of global symbols referenced and not defined.  */
  777. int undefined_global_sym_count;
  778.  
  779. /* Count the number of global symbols multiply defined.  */
  780. int multiple_def_count;
  781.  
  782. /* Count the number of defined global symbols.
  783.    Each symbol is counted only once
  784.    regardless of how many different nlist entries refer to it,
  785.    since the output file will need only one nlist entry for it.
  786.    This count is computed by `digest_symbols';
  787.    it is undefined while symbols are being loaded. */
  788. int defined_global_sym_count;
  789.  
  790. /* Count the number of symbols defined through common declarations.
  791.    This count is kept in symdef_library, linear_library, and
  792.    enter_global_ref.  It is incremented when the defined flag is set
  793.    in a symbol because of a common definition, and decremented when
  794.    the symbol is defined "for real" (ie. by something besides a common
  795.    definition).  */
  796. int common_defined_global_count;
  797.  
  798. /* Count the number of set element type symbols and the number of
  799.    separate vectors which these symbols will fit into.  See the
  800.    GNU a.out.h for more info.
  801.    This count is computed by 'enter_file_symbols' */
  802. int set_symbol_count;
  803. int set_vector_count;
  804.  
  805. /* Define a linked list of strings which define symbols which should
  806.    be treated as set elements even though they aren't.  Any symbol
  807.    with a prefix matching one of these should be treated as a set
  808.    element.
  809.  
  810.    This is to make up for deficiencies in many assemblers which aren't
  811.    willing to pass any stabs through to the loader which they don't
  812.    understand.  */
  813. struct string_list_element {
  814.   char *str;
  815.   struct string_list_element *next;
  816. };
  817.  
  818. struct string_list_element *set_element_prefixes;
  819.  
  820. /* Count the number of definitions done indirectly (ie. done relative
  821.    to the value of some other symbol. */
  822. int global_indirect_count;
  823.  
  824. /* Count the number of warning symbols encountered. */
  825. int warning_count;
  826.  
  827. /* Total number of symbols to be written in the output file.
  828.    Computed by digest_symbols from the variables above.  */
  829. int nsyms;
  830.  
  831.  
  832. /* Nonzero means ptr to symbol entry for symbol to use as start addr.
  833.    -e sets this.  */
  834. symbol *entry_symbol;
  835.  
  836. /* These can be NULL if we don't actually have such a symbol.  */
  837. symbol *edata_symbol;   /* the symbol _edata */
  838. symbol *etext_symbol;   /* the symbol _etext */
  839. symbol *end_symbol;    /* the symbol _end */
  840. /* We also need __{edata,etext,end} so that they can safely
  841.    be used from an ANSI library.  */
  842. symbol *edata_symbol_alt;
  843. symbol *etext_symbol_alt;
  844. symbol *end_symbol_alt;
  845.  
  846. /* Kinds of files potentially understood by the linker. */
  847.  
  848. enum file_type { IS_UNKNOWN, IS_ARCHIVE, IS_A_OUT, IS_MACH_O };
  849.  
  850. /* Each input file, and each library member ("subfile") being loaded,
  851.    has a `file_entry' structure for it.
  852.  
  853.    For files specified by command args, these are contained in the vector
  854.    which `file_table' points to.
  855.  
  856.    For library members, they are dynamically allocated,
  857.    and chained through the `chain' field.
  858.    The chain is found in the `subfiles' field of the `file_entry'.
  859.    The `file_entry' objects for the members have `superfile' fields pointing
  860.    to the one for the library.  */
  861.  
  862. struct file_entry {
  863.   /* Name of this file.  */
  864.   char *filename;
  865.  
  866.   /* What kind of file this is. */
  867.   enum file_type file_type;
  868.  
  869.   /* Name to use for the symbol giving address of text start */
  870.   /* Usually the same as filename, but for a file spec'd with -l
  871.      this is the -l switch itself rather than the filename.  */
  872.   char *local_sym_name;
  873.  
  874.   /* Describe the layout of the contents of the file.  */
  875.  
  876.   /* The text section. */
  877.   unsigned long int orig_text_address;
  878.   unsigned long int text_size;
  879.   long int text_offset;
  880.  
  881.   /* Text relocation. */
  882.   unsigned long int text_reloc_size;
  883.   long int text_reloc_offset;
  884.  
  885.   /* The data section. */
  886.   unsigned long int orig_data_address;
  887.   unsigned long int data_size;
  888.   long int data_offset;
  889.  
  890.   /* Data relocation. */
  891.   unsigned long int data_reloc_size;
  892.   long int data_reloc_offset;
  893.  
  894.   /* The bss section. */
  895.   unsigned long int orig_bss_address;
  896.   unsigned long int bss_size;
  897.  
  898.   /* The symbol and string tables. */
  899.   unsigned long int syms_size;
  900.   long int syms_offset;
  901.   unsigned long int strs_size;
  902.   long int strs_offset;
  903.  
  904.   /* The GDB symbol segment, if any. */
  905.   unsigned long int symseg_size;
  906.   long int symseg_offset;
  907.  
  908. #ifdef MACH_O
  909.   /* Section ordinals from the Mach-O load commands.  These
  910.      are compared with the n_sect fields of symbols.  */
  911.   int text_ordinal;
  912.   int data_ordinal;
  913.   int bss_ordinal;
  914. #endif
  915.  
  916.   /* Describe data from the file loaded into core */
  917.  
  918.   /* Symbol table of the file.  */
  919.   struct nlist *symbols;
  920.  
  921.   /* Pointer to the string table.
  922.      The string table is not kept in core all the time,
  923.      but when it is in core, its address is here.  */
  924.   char *strings;
  925.  
  926.   /* Next two used only if OUTPUT_RELOCATABLE or if needed for */
  927.   /* output of undefined reference line numbers. */
  928.  
  929.   /* Text reloc info saved by `write_text' for `coptxtrel'.  */
  930.   struct relocation_info *textrel;
  931.   /* Data reloc info saved by `write_data' for `copdatrel'.  */
  932.   struct relocation_info *datarel;
  933.  
  934.   /* Relation of this file's segments to the output file */
  935.  
  936.   /* Start of this file's text seg in the output file core image.  */
  937.   int text_start_address;
  938.   /* Start of this file's data seg in the output file core image.  */
  939.   int data_start_address;
  940.   /* Start of this file's bss seg in the output file core image.  */
  941.   int bss_start_address;
  942.   /* Offset in bytes in the output file symbol table
  943.      of the first local symbol for this file.  Set by `write_file_symbols'.  */
  944.   int local_syms_offset;
  945.  
  946.   /* For library members only */
  947.  
  948.   /* For a library, points to chain of entries for the library members.  */
  949.   struct file_entry *subfiles;
  950.   /* For a library member, offset of the member within the archive.
  951.      Zero for files that are not library members.  */
  952.   int starting_offset;
  953.   /* Size of contents of this file, if library member.  */
  954.   int total_size;
  955.   /* For library member, points to the library's own entry.  */
  956.   struct file_entry *superfile;
  957.   /* For library member, points to next entry for next member.  */
  958.   struct file_entry *chain;
  959.  
  960.   /* 1 if file is a library. */
  961.   char library_flag;
  962.  
  963.   /* 1 if file's header has been read into this structure.  */
  964.   char header_read_flag;
  965.  
  966.   /* 1 means search a set of directories for this file.  */
  967.   char search_dirs_flag;
  968.  
  969.   /* 1 means this is base file of incremental load.
  970.      Do not load this file's text or data.
  971.      Also default text_start to after this file's bss. */
  972.   char just_syms_flag;
  973. };
  974.  
  975. /* Vector of entries for input files specified by arguments.
  976.    These are all the input files except for members of specified libraries.  */
  977. struct file_entry *file_table;
  978.  
  979. /* Length of that vector.  */
  980. int number_of_files;
  981.  
  982. /* When loading the text and data, we can avoid doing a close
  983.    and another open between members of the same library.
  984.  
  985.    These two variables remember the file that is currently open.
  986.    Both are zero if no file is open.
  987.  
  988.    See `each_file' and `file_close'.  */
  989.  
  990. struct file_entry *input_file;
  991. int input_desc;
  992.  
  993. /* The name of the file to write; "a.out" by default.  */
  994.  
  995. char *output_filename;
  996.  
  997. /* What kind of output file to write.  */
  998.  
  999. enum file_type output_file_type;
  1000.  
  1001. #ifndef DEFAULT_OUTPUT_FILE_TYPE
  1002. #ifdef MACH_O
  1003. #define DEFAULT_OUTPUT_FILE_TYPE IS_MACH_O
  1004. #else
  1005. #define DEFAULT_OUTPUT_FILE_TYPE IS_A_OUT
  1006. #endif
  1007. #endif
  1008.  
  1009. /* What `style' of output file to write.  For BSD a.out files
  1010.    this specifies OMAGIC, NMAGIC, or ZMAGIC.  For Mach-O files
  1011.    this switches between MH_OBJECT and two flavors of MH_EXECUTE.  */
  1012.  
  1013. enum output_style
  1014.   {
  1015.     OUTPUT_UNSPECIFIED,
  1016.     OUTPUT_RELOCATABLE,        /* -r */
  1017.     OUTPUT_WRITABLE_TEXT,    /* -N */
  1018.     OUTPUT_READONLY_TEXT,    /* -n */
  1019.     OUTPUT_DEMAND_PAGED        /* -Z (default) */
  1020.   };
  1021.  
  1022. enum output_style output_style;
  1023.  
  1024. #ifndef DEFAULT_OUTPUT_STYLE
  1025. #define DEFAULT_OUTPUT_STYLE OUTPUT_DEMAND_PAGED
  1026. #endif
  1027.  
  1028. /* Descriptor for writing that file with `mywrite'.  */
  1029.  
  1030. int outdesc;
  1031.  
  1032. /* The following are computed by `digest_symbols'.  */
  1033.  
  1034. int text_size;            /* total size of text of all input files.  */
  1035. int text_header_size;        /* size of the file header if included in the
  1036.                    text size.  */
  1037. int data_size;            /* total size of data of all input files.  */
  1038. int bss_size;            /* total size of bss of all input files.  */
  1039. int text_reloc_size;        /* total size of text relocation of all input files.  */
  1040. int data_reloc_size;        /* total size of data relocation of all input
  1041.                    files.  */
  1042.   
  1043. /* The following are computed by write_header().  */
  1044. long int output_text_offset;    /* file offset of the text section.  */
  1045. long int output_data_offset;    /* file offset of the data section.  */
  1046. long int output_trel_offset;    /* file offset of the text relocation info.  */
  1047. long int output_drel_offset;    /* file offset of the data relocation info.  */
  1048. long int output_syms_offset;    /* file offset of the symbol table.  */
  1049. long int output_strs_offset;    /* file offset of the string table.  */
  1050.  
  1051. /* The following are incrementally computed by write_syms(); we keep
  1052.    them here so we can examine their values afterwards.  */
  1053. unsigned int output_syms_size;    /* total bytes of symbol table output. */
  1054. unsigned int output_strs_size;    /* total bytes of string table output. */
  1055.  
  1056. /* This can only be computed after the size of the string table is known.  */
  1057. long int output_symseg_offset;    /* file offset of the symbol segment (if any).  */
  1058.  
  1059. /* Incrementally computed by write_file_symseg().  */
  1060. unsigned int output_symseg_size;
  1061.  
  1062. /* Specifications of start and length of the area reserved at the end
  1063.    of the text segment for the set vectors.  Computed in 'digest_symbols' */
  1064. int set_sect_start;
  1065. int set_sect_size;
  1066.  
  1067. /* Pointer for in core storage for the above vectors, before they are
  1068.    written. */
  1069. unsigned long *set_vectors;
  1070.  
  1071. /* Amount of cleared space to leave at the end of the text segment.  */
  1072.  
  1073. int text_pad;
  1074.  
  1075. /* Amount of padding at end of data segment.  This has two parts:
  1076.    That which is before the bss segment, and that which overlaps
  1077.    with the bss segment.  */
  1078. int data_pad;
  1079.  
  1080. /* Format of __.SYMDEF:
  1081.    First, a longword containing the size of the 'symdef' data that follows.
  1082.    Second, zero or more 'symdef' structures.
  1083.    Third, a longword containing the length of symbol name strings.
  1084.    Fourth, zero or more symbol name strings (each followed by a null).  */
  1085.  
  1086. struct symdef {
  1087.   int symbol_name_string_index;
  1088.   int library_member_offset;
  1089. };
  1090.  
  1091. /* Record most of the command options.  */
  1092.  
  1093. /* Address we assume the text section will be loaded at.
  1094.    We relocate symbols and text and data for this, but we do not
  1095.    write any padding in the output file for it.  */
  1096. int text_start;
  1097.  
  1098. /* Address we decide the data section will be loaded at.  */
  1099. int data_start;
  1100.  
  1101. /* Nonzero if -T was specified in the command line.
  1102.    This prevents text_start from being set later to default values.  */
  1103. int T_flag_specified;
  1104.  
  1105. /* Nonzero if -Tdata was specified in the command line.
  1106.    This prevents data_start from being set later to default values.  */
  1107. int Tdata_flag_specified;
  1108.  
  1109. /* Size to pad data section up to.
  1110.    We simply increase the size of the data section, padding with zeros,
  1111.    and reduce the size of the bss section to match.  */
  1112. int specified_data_size;
  1113.  
  1114. #ifdef sprite
  1115. /* Gap to insert between end of bss and start of data seg */
  1116. int data_gap;
  1117.  
  1118. /* Nonzero if -Z was specified (for data_gap) */
  1119. int Z_flag_specified;
  1120. #endif
  1121.  
  1122. /* Nonzero means print names of input files as processed.  */
  1123. int trace_files;
  1124.  
  1125. /* Which symbols should be stripped (omitted from the output):
  1126.    none, all, or debugger symbols.  */
  1127. enum { STRIP_NONE, STRIP_ALL, STRIP_DEBUGGER } strip_symbols;
  1128.  
  1129. /* Which local symbols should be omitted:
  1130.    none, all, or those starting with L.
  1131.    This is irrelevant if STRIP_NONE.  */
  1132. enum { DISCARD_NONE, DISCARD_ALL, DISCARD_L } discard_locals;
  1133.  
  1134. /* 1 => write load map.  */
  1135. int write_map;
  1136.  
  1137. /* 1 => assign space to common symbols even if OUTPUT_RELOCATABLE. */
  1138. int force_common_definition;
  1139.  
  1140. /* Standard directories to search for files specified by -l.  */
  1141. char *standard_search_dirs[] =
  1142. #ifdef STANDARD_SEARCH_DIRS
  1143.   {STANDARD_SEARCH_DIRS};
  1144. #else
  1145. #ifdef NON_NATIVE
  1146.   {"/usr/local/lib/gnu"};
  1147. #else
  1148.   {"/lib", "/usr/lib", "/usr/local/lib"};
  1149. #endif
  1150. #endif
  1151.  
  1152. /* If set STANDARD_SEARCH_DIRS is not searched.  */
  1153. int no_standard_dirs;
  1154.  
  1155. /* Actual vector of directories to search;
  1156.    this contains those specified with -L plus the standard ones.  */
  1157. char **search_dirs;
  1158.  
  1159. /* Length of the vector `search_dirs'.  */
  1160. int n_search_dirs;
  1161.  
  1162. /* Non zero means to create the output executable.
  1163.    Cleared by nonfatal errors.  */
  1164. int make_executable;
  1165.  
  1166. /* Force the executable to be output, even if there are non-fatal
  1167.    errors */
  1168. int force_executable;
  1169.  
  1170. /* Keep a list of any symbols referenced from the command line (so
  1171.    that error messages for these guys can be generated). This list is
  1172.    zero terminated. */
  1173. struct glosym **cmdline_references;
  1174. int cl_refs_allocated;
  1175.  
  1176. #ifndef bcopy
  1177. void bcopy (), bzero ();
  1178. #endif
  1179. char *malloc (), *realloc ();
  1180. void free ();
  1181.  
  1182. char *xmalloc ();
  1183. char *xrealloc ();
  1184. void usage ();
  1185. void fatal ();
  1186. void fatal_with_file ();
  1187. void perror_name ();
  1188. void perror_file ();
  1189. void error ();
  1190.  
  1191. int parse ();
  1192. void initialize_text_start ();
  1193. void initialize_data_start ();
  1194. void digest_symbols ();
  1195. void print_symbols ();
  1196. void load_symbols ();
  1197. void decode_command ();
  1198. void list_undefined_symbols ();
  1199. void list_unresolved_references ();
  1200. void write_output ();
  1201. void write_header ();
  1202. void write_text ();
  1203. void read_file_relocation ();
  1204. void write_data ();
  1205. void write_rel ();
  1206. void write_syms ();
  1207. void write_symsegs ();
  1208. void mywrite ();
  1209. void symtab_init ();
  1210. void padfile ();
  1211. char *concat ();
  1212. char *get_file_name ();
  1213. symbol *getsym (), *getsym_soft ();
  1214.  
  1215. int
  1216. main (argc, argv)
  1217.      char **argv;
  1218.      int argc;
  1219. {
  1220. #ifdef TARGET_PAGE_SIZE
  1221.   page_size = TARGET_PAGE_SIZE;
  1222. #else
  1223.   page_size = getpagesize ();
  1224. #endif
  1225.   progname = argv[0];
  1226.  
  1227. #ifdef RLIMIT_STACK
  1228.   /* Avoid dumping core on large .o files.  */
  1229.   {
  1230.     struct rlimit rl;
  1231.  
  1232.     getrlimit (RLIMIT_STACK, &rl);
  1233.     rl.rlim_cur = rl.rlim_max;
  1234.     setrlimit (RLIMIT_STACK, &rl);
  1235.   }
  1236. #endif
  1237.  
  1238.   /* Clear the cumulative info on the output file.  */
  1239.  
  1240.   text_size = 0;
  1241.   data_size = 0;
  1242.   bss_size = 0;
  1243.   text_reloc_size = 0;
  1244.   data_reloc_size = 0;
  1245.  
  1246.   data_pad = 0;
  1247.   text_pad = 0;
  1248.  
  1249.   /* Initialize the data about options.  */
  1250.  
  1251.   specified_data_size = 0;
  1252.   strip_symbols = STRIP_NONE;
  1253.   trace_files = 0;
  1254.   discard_locals = DISCARD_NONE;
  1255.   entry_symbol = 0;
  1256.   write_map = 0;
  1257.   force_common_definition = 0;
  1258.   T_flag_specified = 0;
  1259.   Tdata_flag_specified = 0;
  1260.   make_executable = 1;
  1261.   force_executable = 0;
  1262.   set_element_prefixes = 0;
  1263.   Z_flag_specified = 0;
  1264.  
  1265.   /* Initialize the cumulative counts of symbols.  */
  1266.  
  1267.   local_sym_count = 0;
  1268.   non_L_local_sym_count = 0;
  1269.   debugger_sym_count = 0;
  1270.   undefined_global_sym_count = 0;
  1271.   set_symbol_count = 0;
  1272.   set_vector_count = 0;
  1273.   global_indirect_count = 0;
  1274.   warning_count = 0;
  1275.   multiple_def_count = 0;
  1276.   common_defined_global_count = 0;
  1277.  
  1278.   /* Keep a list of symbols referenced from the command line */
  1279.  
  1280.   cl_refs_allocated = 10;
  1281.   cmdline_references =
  1282.     (struct glosym **) xmalloc (cl_refs_allocated
  1283.                   * sizeof(struct glosym *));
  1284.   *cmdline_references = 0;
  1285.  
  1286.   /* Completely decode ARGV.  */
  1287.  
  1288.   decode_command (argc, argv);
  1289.  
  1290.   /* Load symbols of all input files.
  1291.      Also search all libraries and decide which library members to load.  */
  1292.  
  1293.   load_symbols ();
  1294.  
  1295.   /* Create various built-in symbols.  This must occur after
  1296.      all input files are loaded so that a user program can have a
  1297.      symbol named etext (for example).  */
  1298.  
  1299.   if (output_style != OUTPUT_RELOCATABLE)
  1300.     symtab_init ();
  1301.  
  1302.   /* Compute where each file's sections go, and relocate symbols.  */
  1303.  
  1304.   digest_symbols ();
  1305.  
  1306.   /* Print error messages for any missing symbols, for any warning
  1307.      symbols, and possibly multiple definitions */
  1308.  
  1309.   do_warnings (stderr);
  1310.  
  1311.   /* Print a map, if requested.  */
  1312.  
  1313.   if (write_map) print_symbols (stdout);
  1314.  
  1315.   /* Write the output file.  */
  1316.  
  1317.   if (make_executable || force_executable)
  1318.     write_output ();
  1319.  
  1320.   exit (!make_executable);
  1321. }
  1322.  
  1323. void add_cmdline_ref ();
  1324.  
  1325. static struct option longopts[] =
  1326. {
  1327.   {"d", 0, 0, 'd'},
  1328.   {"dc", 0, 0, 'd'},        /* For Sun compatibility. */
  1329.   {"dp", 0, 0, 'd'},        /* For Sun compatibility. */
  1330.   {"e", 1, 0, 'e'},
  1331.   {"n", 0, 0, 'n'},
  1332.   {"noinhibit-exec", 0, 0, 130},
  1333.   {"nostdlib", 0, 0, 133},
  1334.   {"o", 1, 0, 'o'},
  1335.   {"r", 0, 0, 'r'},
  1336.   {"s", 0, 0, 's'},
  1337.   {"t", 0, 0, 't'},
  1338.   {"u", 1, 0, 'u'},
  1339.   {"x", 0, 0, 'x'},
  1340.   {"z", 0, 0, 'z'},
  1341.   {"A", 1, 0, 'A'},
  1342.   {"Bstatic", 0, 0, 129},    /* For Sun compatibility. */
  1343.   {"D", 1, 0, 'D'},
  1344.   {"M", 0, 0, 'M'},
  1345.   {"N", 0, 0, 'N'},
  1346.   {"S", 0, 0, 'S'},
  1347.   {"T", 1, 0, 'T'},
  1348.   {"Ttext", 1, 0, 'T'},
  1349.   {"Tdata", 1, 0, 132},
  1350.   {"V", 1, 0, 'V'},
  1351.   {"X", 0, 0, 'X'},
  1352.   {0, 0, 0, 0}
  1353. };
  1354.  
  1355. /* Since the Unix ld accepts -lfoo, -Lfoo, and -yfoo, we must also.
  1356.    This effectively prevents any long options from starting with
  1357.    one of these letters. */
  1358. #define SHORTOPTS "-l:y:L:"
  1359.  
  1360. /* Process the command arguments,
  1361.    setting up file_table with an entry for each input file,
  1362.    and setting variables according to the options.  */
  1363.  
  1364. void
  1365. decode_command (argc, argv)
  1366.      char **argv;
  1367.      int argc;
  1368. {
  1369.   int optc, longind;
  1370.   register struct file_entry *p;
  1371.  
  1372.   number_of_files = 0;
  1373.   output_filename = "a.out";
  1374.  
  1375.   n_search_dirs = 0;
  1376.   search_dirs = (char **) xmalloc (sizeof (char *));
  1377.  
  1378.   /* First compute number_of_files so we know how long to make file_table.
  1379.      Also process most options completely.  */
  1380.  
  1381.   while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
  1382.      != EOF)
  1383.     {
  1384.       if (optc == 0)
  1385.     optc = longopts[longind].val;
  1386.  
  1387.       switch (optc)
  1388.     {
  1389.     case '?':
  1390.       usage (0, 0);
  1391.       break;
  1392.  
  1393.     case 1:
  1394.       /* Non-option argument. */
  1395.       number_of_files++;
  1396.       break;
  1397.  
  1398.     case 'd':
  1399.       force_common_definition = 1;
  1400.       break;
  1401.  
  1402.     case 'e':
  1403.       entry_symbol = getsym (optarg);
  1404.       if (!entry_symbol->defined && !entry_symbol->referenced)
  1405.         undefined_global_sym_count++;
  1406.       entry_symbol->referenced = 1;
  1407.       add_cmdline_ref (entry_symbol);
  1408.       break;
  1409.  
  1410. #if TARGET==TARGET_SEQUENT
  1411.       /*
  1412.        * k == Symmetry standalone,
  1413.        */
  1414.         case 'k':
  1415. #ifdef SMAGIC
  1416.       magic = SMAGIC;
  1417. #else
  1418.       fatal("No SMAGIC defined for -k");
  1419. #endif
  1420.       return;
  1421. #endif
  1422.  
  1423.     case 'l':
  1424.       number_of_files++;
  1425.       break;
  1426.  
  1427.     case 'n':
  1428.       if (output_style && output_style != OUTPUT_READONLY_TEXT)
  1429.         fatal ("illegal combination of -n with -N, -r, or -z", (char *) 0);
  1430.       output_style = OUTPUT_READONLY_TEXT;
  1431.       break;
  1432.  
  1433.     case 130:        /* -noinhibit-exec */
  1434.       force_executable = 1;
  1435.       break;
  1436.  
  1437.     case 133:        /* -nostdlib */
  1438.       no_standard_dirs = 1;
  1439.       break;
  1440.  
  1441.     case 'o':
  1442.       output_filename = optarg;
  1443.       break;
  1444.  
  1445. #if TARGET==TARGET_SEQUENT
  1446.       /*
  1447.        * p == don't align text/data boundary (for 8K disk bootstraps).
  1448.        */
  1449.          case 'p':
  1450.        break;
  1451. #endif
  1452.  
  1453.     case 'r':
  1454.       if (output_style && output_style != OUTPUT_RELOCATABLE)
  1455.         fatal ("illegal combination of -r with -N, -n, or -z", (char *) 0);
  1456.       output_style = OUTPUT_RELOCATABLE;
  1457.       text_start = 0;
  1458.       break;
  1459.  
  1460.     case 's':
  1461.       strip_symbols = STRIP_ALL;
  1462.       break;
  1463.  
  1464.     case 't':
  1465.       trace_files = 1;
  1466.       break;
  1467.  
  1468.     case 'u':
  1469.       {
  1470.         register symbol *sp = getsym (optarg);
  1471.  
  1472.         if (!sp->defined && !sp->referenced)
  1473.           undefined_global_sym_count++;
  1474.         sp->referenced = 1;
  1475.         add_cmdline_ref (sp);
  1476.       }
  1477.       break;
  1478.  
  1479.     case 'x':
  1480.       discard_locals = DISCARD_ALL;
  1481.       break;
  1482.  
  1483.     case 'y':
  1484.       {
  1485.         register symbol *sp = getsym (optarg);
  1486.  
  1487.         sp->trace = 1;
  1488.       }
  1489.       break;
  1490.  
  1491.     case 'z':
  1492.       if (output_style && output_style != OUTPUT_DEMAND_PAGED)
  1493.         fatal ("illegal combination of -z with -N, -n, or -r", (char *) 0);
  1494.       output_style = OUTPUT_DEMAND_PAGED;
  1495.       break;
  1496.  
  1497.     case 'A':
  1498.       number_of_files++;
  1499.       break;
  1500.  
  1501.     case 129:        /* -Bstatic. */
  1502.       /* Ignore. */
  1503.       break;
  1504.  
  1505.     case 'D':
  1506.       specified_data_size = parse (optarg, "%x", "invalid argument to -D");
  1507.       break;
  1508.  
  1509.     case 'L':
  1510.       n_search_dirs++;
  1511.       search_dirs = (char **)
  1512.         xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1513.       search_dirs[n_search_dirs - 1] = optarg;
  1514.       break;
  1515.  
  1516.     case 'M':
  1517.       write_map = 1;
  1518.       break;
  1519.  
  1520.     case 'N':
  1521.       if (output_style && output_style != OUTPUT_WRITABLE_TEXT)
  1522.         fatal ("illegal combination of -N with -n, -r, or -z", (char *) 0);
  1523.       output_style = OUTPUT_WRITABLE_TEXT;
  1524.       break;
  1525.  
  1526.     case 'S':
  1527.       strip_symbols = STRIP_DEBUGGER;
  1528.       break;
  1529.  
  1530.         case 'T':
  1531.       text_start = parse (optarg, "%x", "invalid argument to -Ttext");
  1532.       T_flag_specified = 1;
  1533. #ifdef sprite
  1534.       output_style = OUTPUT_WRITABLE_TEXT;
  1535. #endif
  1536.       break;
  1537.  
  1538.     case 132:        /* -Tdata addr */
  1539.       data_start = parse (optarg, "%x", "invalid argument to -Tdata");
  1540.       Tdata_flag_specified = 1;
  1541.       break;
  1542.  
  1543.     case 'V':
  1544.       {
  1545.         struct string_list_element *new
  1546.           = (struct string_list_element *)
  1547.         xmalloc (sizeof (struct string_list_element));
  1548.  
  1549.         new->str = optarg;
  1550.         new->next = set_element_prefixes;
  1551.         set_element_prefixes = new;
  1552.       }
  1553.       break;
  1554.  
  1555.     case 'X':
  1556.       discard_locals = DISCARD_L;
  1557.       break;
  1558.  
  1559.     }
  1560.     }
  1561.  
  1562.   if (!number_of_files)
  1563.     usage ("no input files", 0);
  1564.  
  1565.   p = file_table
  1566.     = (struct file_entry *) xmalloc (number_of_files * sizeof (struct file_entry));
  1567.   bzero (p, number_of_files * sizeof (struct file_entry));
  1568.  
  1569.   /* Now scan again and fill in file_table.
  1570.      All options except -A and -l are ignored here.  */
  1571.  
  1572.   optind = 0;            /* Reset getopt. */
  1573.   while ((optc = getopt_long_only (argc, argv, SHORTOPTS, longopts, &longind))
  1574.      != EOF)
  1575.     {
  1576.       if (optc == 0)
  1577.     optc = longopts[longind].val;
  1578.  
  1579.       switch (optc)
  1580.     {
  1581.     case 1:
  1582.       /* Non-option argument. */
  1583.       p->filename = optarg;
  1584.       p->local_sym_name = optarg;
  1585.       p++;
  1586.       break;
  1587.  
  1588.     case 'A':
  1589.       if (p != file_table)
  1590.         usage ("-A specified before an input file other than the first");
  1591.       p->filename = optarg;
  1592.       p->local_sym_name = optarg;
  1593.       p->just_syms_flag = 1;
  1594.       p++;
  1595.       break;
  1596.  
  1597.     case 'l':
  1598.       p->filename = concat ("lib", optarg, ".a");
  1599.       p->local_sym_name = concat ("-l", optarg, "");
  1600.       p->search_dirs_flag = 1;
  1601.       p++;
  1602.       break;
  1603.     }
  1604.     }
  1605.  
  1606.   if (!output_file_type)
  1607.     output_file_type = DEFAULT_OUTPUT_FILE_TYPE;
  1608.  
  1609.   if (!output_style)
  1610.     output_style = DEFAULT_OUTPUT_STYLE;
  1611.  
  1612. #if 0
  1613.   /* THIS CONSISTENCY CHECK BELONGS SOMEWHERE ELSE.  */
  1614.   /* Now check some option settings for consistency.  */
  1615.  
  1616.   if ((output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
  1617.       && (text_start - text_start_alignment) & (page_size - 1))
  1618.     usage ("-T argument not multiple of page size, with sharable output", 0);
  1619. #endif
  1620.  
  1621.   /* Append the standard search directories to the user-specified ones.  */
  1622.   if (!no_standard_dirs)
  1623.     {
  1624.       int n = sizeof standard_search_dirs / sizeof standard_search_dirs[0];
  1625.       n_search_dirs += n;
  1626.       search_dirs
  1627.     = (char **) xrealloc (search_dirs, n_search_dirs * sizeof (char *));
  1628.       bcopy (standard_search_dirs, &search_dirs[n_search_dirs - n],
  1629.          n * sizeof (char *));
  1630.     }
  1631. }
  1632.  
  1633.  
  1634. void
  1635. add_cmdline_ref (sp)
  1636.      struct glosym *sp;
  1637. {
  1638.   struct glosym **ptr;
  1639.  
  1640.   for (ptr = cmdline_references;
  1641.        ptr < cmdline_references + cl_refs_allocated && *ptr;
  1642.        ptr++)
  1643.     ;
  1644.  
  1645.   if (ptr >= cmdline_references + cl_refs_allocated - 1)
  1646.     {
  1647.       int diff = ptr - cmdline_references;
  1648.  
  1649.       cl_refs_allocated *= 2;
  1650.       cmdline_references = (struct glosym **)
  1651.     xrealloc (cmdline_references,
  1652.          cl_refs_allocated * sizeof (struct glosym *));
  1653.       ptr = cmdline_references + diff;
  1654.     }
  1655.  
  1656.   *ptr++ = sp;
  1657.   *ptr = (struct glosym *) 0;
  1658. }
  1659.  
  1660. int
  1661. set_element_prefixed_p (name)
  1662.      char *name;
  1663. {
  1664.   struct string_list_element *p;
  1665.   int i;
  1666.  
  1667.   for (p = set_element_prefixes; p; p = p->next)
  1668.     {
  1669.       for (i = 0; p->str[i] != '\0' && (p->str[i] == name[i]); i++)
  1670.     ;
  1671.  
  1672.       if (p->str[i] == '\0')
  1673.     return 1;
  1674.     }
  1675.   return 0;
  1676. }
  1677.  
  1678. /* Convenient functions for operating on one or all files being
  1679.    loaded.  */
  1680. void print_file_name ();
  1681.  
  1682. /* Call FUNCTION on each input file entry.
  1683.    Do not call for entries for libraries;
  1684.    instead, call once for each library member that is being loaded.
  1685.  
  1686.    FUNCTION receives two arguments: the entry, and ARG.  */
  1687.  
  1688. void
  1689. each_file (function, arg)
  1690.      register void (*function)();
  1691.      register int arg;
  1692. {
  1693.   register int i;
  1694.  
  1695.   for (i = 0; i < number_of_files; i++)
  1696.     {
  1697.       register struct file_entry *entry = &file_table[i];
  1698.       if (entry->library_flag)
  1699.         {
  1700.       register struct file_entry *subentry = entry->subfiles;
  1701.       for (; subentry; subentry = subentry->chain)
  1702.         (*function) (subentry, arg);
  1703.     }
  1704.       else
  1705.     (*function) (entry, arg);
  1706.     }
  1707. }
  1708. #if 0
  1709. /* Call FUNCTION on each input file entry until it returns a non-zero
  1710.    value.  Return this value.
  1711.    Do not call for entries for libraries;
  1712.    instead, call once for each library member that is being loaded.
  1713.  
  1714.    FUNCTION receives two arguments: the entry, and ARG.  It must be a
  1715.    function returning unsigned long (though this can probably be fudged). */
  1716.  
  1717. unsigned long
  1718. check_each_file (function, arg)
  1719.      register unsigned long (*function)();
  1720.      register int arg;
  1721. {
  1722.   register int i;
  1723.   register unsigned long return_val;
  1724.  
  1725.   for (i = 0; i < number_of_files; i++)
  1726.     {
  1727.       register struct file_entry *entry = &file_table[i];
  1728.       if (entry->library_flag)
  1729.         {
  1730.       register struct file_entry *subentry = entry->subfiles;
  1731.       for (; subentry; subentry = subentry->chain)
  1732.         if (return_val = (*function) (subentry, arg))
  1733.           return return_val;
  1734.     }
  1735.       else
  1736.     if (return_val = (*function) (entry, arg))
  1737.       return return_val;
  1738.     }
  1739.   return 0;
  1740. }
  1741. #endif
  1742. /* Like `each_file' but ignore files that were just for symbol definitions.  */
  1743.  
  1744. void
  1745. each_full_file (function, arg)
  1746.      register void (*function)();
  1747.      register int arg;
  1748. {
  1749.   register int i;
  1750.  
  1751.   for (i = 0; i < number_of_files; i++)
  1752.     {
  1753.       register struct file_entry *entry = &file_table[i];
  1754.       if (entry->just_syms_flag)
  1755.     continue;
  1756.       if (entry->library_flag)
  1757.         {
  1758.       register struct file_entry *subentry = entry->subfiles;
  1759.       for (; subentry; subentry = subentry->chain)
  1760.         (*function) (subentry, arg);
  1761.     }
  1762.       else
  1763.     (*function) (entry, arg);
  1764.     }
  1765. }
  1766.  
  1767. /* Close the input file that is now open.  */
  1768.  
  1769. void
  1770. file_close ()
  1771. {
  1772.   close (input_desc);
  1773.   input_desc = 0;
  1774.   input_file = 0;
  1775. }
  1776.  
  1777. /* Open the input file specified by 'entry', and return a descriptor.
  1778.    The open file is remembered; if the same file is opened twice in a row,
  1779.    a new open is not actually done.  */
  1780.  
  1781. int
  1782. file_open (entry)
  1783.      register struct file_entry *entry;
  1784. {
  1785.   register int desc;
  1786.  
  1787.   if (entry->superfile)
  1788.     return file_open (entry->superfile);
  1789.  
  1790.   if (entry == input_file)
  1791.     return input_desc;
  1792.  
  1793.   if (input_file) file_close ();
  1794.  
  1795.   if (entry->search_dirs_flag && n_search_dirs)
  1796.     {
  1797.       int i;
  1798.  
  1799.       for (i = 0; i < n_search_dirs; i++)
  1800.     {
  1801.       register char *string
  1802.         = concat (search_dirs[i], "/", entry->filename);
  1803.       desc = open (string, O_RDONLY, 0);
  1804.       if (desc > 0)
  1805.         {
  1806.           entry->filename = string;
  1807.           entry->search_dirs_flag = 0;
  1808.           break;
  1809.         }
  1810.       free (string);
  1811.     }
  1812.     }
  1813.   else
  1814.     desc = open (entry->filename, O_RDONLY, 0);
  1815.  
  1816.   if (desc > 0)
  1817.     {
  1818.       input_file = entry;
  1819.       input_desc = desc;
  1820.       return desc;
  1821.     }
  1822.  
  1823.   perror_file (entry);
  1824.   /* NOTREACHED */
  1825. }
  1826.  
  1827. /* Print the filename of ENTRY on OUTFILE (a stdio stream),
  1828.    and then a newline.  */
  1829.  
  1830. void
  1831. prline_file_name (entry, outfile)
  1832.      struct file_entry *entry;
  1833.      FILE *outfile;
  1834. {
  1835.   print_file_name (entry, outfile);
  1836.   fprintf (outfile, "\n");
  1837. }
  1838.  
  1839. /* Print the filename of ENTRY on OUTFILE (a stdio stream).  */
  1840.  
  1841. void
  1842. print_file_name (entry, outfile)
  1843.      struct file_entry *entry;
  1844.      FILE *outfile;
  1845. {
  1846.   if (entry->superfile)
  1847.     {
  1848.       print_file_name (entry->superfile, outfile);
  1849.       fprintf (outfile, "(%s)", entry->filename);
  1850.     }
  1851.   else
  1852.     fprintf (outfile, "%s", entry->filename);
  1853. }
  1854.  
  1855. /* Return the filename of entry as a string (malloc'd for the purpose) */
  1856.  
  1857. char *
  1858. get_file_name (entry)
  1859.      struct file_entry *entry;
  1860. {
  1861.   char *result, *supfile;
  1862.   if (entry->superfile)
  1863.     {
  1864.       supfile = get_file_name (entry->superfile);
  1865.       result = (char *) xmalloc (strlen (supfile)
  1866.                  + strlen (entry->filename) + 3);
  1867.       sprintf (result, "%s(%s)", supfile, entry->filename);
  1868.       free (supfile);
  1869.     }
  1870.   else
  1871.     {
  1872.       result = (char *) xmalloc (strlen (entry->filename) + 1);
  1873.       strcpy (result, entry->filename);
  1874.     }
  1875.   return result;
  1876. }
  1877.  
  1878. /* Medium-level input routines for rel files.  */
  1879.  
  1880. /* Determine whether the given ENTRY is an archive, a BSD a.out file,
  1881.    a Mach-O file, or whatever.  DESC is the descriptor on which the
  1882.    file is open.  */
  1883. void
  1884. deduce_file_type(desc, entry)
  1885.      int desc;
  1886.      struct file_entry *entry;
  1887. {
  1888.   int len;
  1889.  
  1890.   {
  1891.     char magic[SARMAG];
  1892.     
  1893.     lseek (desc, entry->starting_offset, 0);
  1894.     len = read (desc, magic, SARMAG);
  1895.     if (len == SARMAG && !strncmp(magic, ARMAG, SARMAG))
  1896.       {
  1897.     entry->file_type = IS_ARCHIVE;
  1898.     return;
  1899.       }
  1900.   }
  1901.  
  1902. #ifdef A_OUT
  1903.   {
  1904.     struct exec hdr;
  1905.  
  1906.     lseek (desc, entry->starting_offset, 0);
  1907. #ifdef COFF_ENCAPSULATE
  1908.     if (entry->just_syms_flag)
  1909.       /* Since a file given with -A will have a coff header, unlike normal
  1910.     input files, we need to skip over it.  */
  1911.       lseek (desc, sizeof (coffheader), SEEK_CUR);
  1912. #endif
  1913.     len = read (desc, (char *) &hdr, sizeof (struct exec));
  1914. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  1915.   fix_exec_header_byte_order(&hdr);
  1916. #endif
  1917.     if (len == sizeof (struct exec) && !N_BADMAG (hdr))
  1918.       {
  1919.     entry->file_type = IS_A_OUT;
  1920.     return;
  1921.       }
  1922.   }
  1923. #endif
  1924.  
  1925. #ifdef MACH_O
  1926.   {
  1927.     struct mach_header hdr;
  1928.  
  1929.     lseek (desc, entry->starting_offset, 0);
  1930.     len = read (desc, (char *) &hdr, sizeof (struct mach_header));
  1931.     if (len == sizeof (struct mach_header) && hdr.magic == MH_MAGIC)
  1932.       {
  1933.     entry->file_type = IS_MACH_O;
  1934.     return;
  1935.       }
  1936.   }
  1937. #endif
  1938.  
  1939.   fatal_with_file ("malformed input file (not rel or archive) ", entry);
  1940. }
  1941.  
  1942. #ifdef A_OUT
  1943. /* Read an a.out file's header and set up the fields of
  1944.    the ENTRY accordingly.  DESC is the descriptor on which
  1945.    the file is open.  */
  1946. void
  1947. read_a_out_header (desc, entry)
  1948.      int desc;
  1949.      struct file_entry *entry;
  1950. {
  1951.   register int len;
  1952.   struct exec hdr;
  1953.   struct stat st;
  1954.  
  1955.   lseek (desc, entry->starting_offset, 0);
  1956.  
  1957. #ifdef COFF_ENCAPSULATE
  1958.   if (entry->just_syms_flag)
  1959.     /* Since a file given with -A will have a coff header, unlike normal
  1960.        input files, we need to skip over it.  */
  1961.     lseek (desc, sizeof (coffheader), SEEK_CUR);
  1962. #endif
  1963.  
  1964.   read (desc, (char *) &hdr, sizeof (struct exec));
  1965.  
  1966. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  1967.   fix_exec_header_byte_order(&hdr);
  1968. #endif
  1969.  
  1970. #ifdef READ_HEADER_HOOK
  1971.   READ_HEADER_HOOK(hdr.a_machtype);
  1972. #endif
  1973.  
  1974.   if (entry->just_syms_flag)
  1975.     entry->orig_text_address = N_TXTADDR(hdr);
  1976.   else
  1977.     entry->orig_text_address = 0;
  1978.   entry->text_size = hdr.a_text;
  1979.   entry->text_offset = N_TXTOFF(hdr);
  1980.  
  1981.   entry->text_reloc_size = hdr.a_trsize;
  1982. #ifdef N_TRELOFF
  1983.   entry->text_reloc_offset = N_TRELOFF(hdr);
  1984. #else
  1985. #ifdef N_DATOFF
  1986.   entry->text_reloc_offset = N_DATOFF(hdr) + hdr.a_data;
  1987. #else
  1988.   entry->text_reloc_offset = N_TXTOFF(hdr) + hdr.a_text + hdr.a_data;
  1989. #endif
  1990. #endif
  1991.  
  1992.   if (entry->just_syms_flag)
  1993.     entry->orig_data_address = N_DATADDR(hdr);
  1994.   else
  1995.     entry->orig_data_address = entry->text_size;
  1996.   entry->data_size = hdr.a_data;
  1997. #ifdef N_DATOFF
  1998.   entry->data_offset = N_DATOFF(hdr);
  1999. #else
  2000.   entry->data_offset = N_TXTOFF(hdr) + hdr.a_text;
  2001. #endif
  2002.  
  2003.   entry->data_reloc_size = hdr.a_drsize;
  2004. #ifdef N_DRELOFF
  2005.   entry->data_reloc_offset = N_DRELOFF(hdr);
  2006. #else
  2007.   entry->data_reloc_offset = entry->text_reloc_offset + entry->text_reloc_size;
  2008. #endif
  2009.  
  2010. #ifdef N_BSSADDR
  2011.   if (entry->just_syms_flag)
  2012.     entry->orig_bss_address = N_BSSADDR(hdr);
  2013.   else
  2014. #endif
  2015.   entry->orig_bss_address = entry->orig_data_address + entry->data_size;
  2016.   entry->bss_size = hdr.a_bss;
  2017.  
  2018.   entry->syms_size = hdr.a_syms;
  2019.   entry->syms_offset = N_SYMOFF(hdr);
  2020.   entry->strs_offset = N_STROFF(hdr);
  2021.   lseek(desc, entry->starting_offset + entry->strs_offset, 0);
  2022.   if (read(desc, (char *) &entry->strs_size, sizeof (unsigned long int))
  2023.       != sizeof (unsigned long int))
  2024.     fatal_with_file ("failure reading string table size of ", entry);
  2025.  
  2026. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2027.   fix_byte_order(&entry->strs_size, sizeof (unsigned long int));
  2028. #endif
  2029.  
  2030.   if (!entry->superfile)
  2031.     {
  2032.       fstat(desc, &st);
  2033.       if (st.st_size > entry->strs_offset + entry->strs_size)
  2034.     {
  2035.       entry->symseg_size = st.st_size - (entry->strs_offset + entry->strs_size);
  2036.       entry->symseg_offset = entry->strs_offset + entry->strs_size;
  2037.     }
  2038.     }
  2039.   else
  2040.     if (entry->total_size > entry->strs_offset + entry->strs_size)
  2041.       {
  2042.     entry->symseg_size = entry->total_size - (entry->strs_offset + entry->strs_size);
  2043.     entry->symseg_offset = entry->strs_offset + entry->strs_size;
  2044.       }
  2045. }
  2046. #endif
  2047.  
  2048. #ifdef MACH_O
  2049. /* Read a Mach-O file's header.  DESC is the descriptor on which the
  2050.    file is open, and ENTRY is the file's entry.  */
  2051. void
  2052. read_mach_o_header (desc, entry)
  2053.      int desc;
  2054.      struct file_entry *entry;
  2055. {
  2056.   struct mach_header mach_header;
  2057.   char *hdrbuf;
  2058.   struct load_command *load_command;
  2059.   struct segment_command *segment_command;
  2060.   struct section *section;
  2061.   struct symtab_command *symtab_command;
  2062. #ifdef LC_SYMSEG
  2063.   struct symseg_command *symseg_command;
  2064. #endif;
  2065.   int ordinal;
  2066.   int symtab_seen, symseg_seen;
  2067.   int len, cmd, seg;
  2068.  
  2069.   entry->text_ordinal = entry->data_ordinal = entry->bss_ordinal = 0;
  2070.   symtab_seen = symseg_seen = 0;
  2071.   ordinal = 1;
  2072.  
  2073.   lseek (desc, entry->starting_offset, 0);
  2074.   len = read (desc, (char *) &mach_header, sizeof (struct mach_header));
  2075.   if (len != sizeof (struct mach_header))
  2076.     fatal_with_file ("failure reading Mach-O header of ", entry);
  2077.   if (mach_header.filetype != MH_OBJECT && mach_header.filetype != MH_EXECUTE)
  2078.     fatal_with_file ("unsupported Mach-O file type (not MH_OBJECT or MH_EXECUTE) in ", entry);
  2079.   hdrbuf = xmalloc (mach_header.sizeofcmds);
  2080.   len = read (desc, hdrbuf, mach_header.sizeofcmds);
  2081.   if (len != mach_header.sizeofcmds)
  2082.     fatal_with_file ("failure reading Mach-O load commands of ", entry);
  2083.   load_command = (struct load_command *) hdrbuf;
  2084.   for (cmd = 0; cmd < mach_header.ncmds; ++cmd)
  2085.     {
  2086.       switch (load_command->cmd)
  2087.     {
  2088.     case LC_SEGMENT:
  2089.       segment_command = (struct segment_command *) load_command;
  2090.       section = (struct section *) ((char *) (segment_command + 1));
  2091.       for (seg = 0; seg < segment_command->nsects; ++seg, ++section, ++ordinal)
  2092.         {
  2093.           if (!strncmp(SECT_TEXT, section->sectname, sizeof section->sectname))
  2094.         if (entry->text_ordinal)
  2095.           fatal_with_file ("more than one __text section in ", entry);
  2096.         else
  2097.           {
  2098.             entry->text_ordinal = ordinal;
  2099.             entry->orig_text_address = section->addr;
  2100.             entry->text_size = section->size;
  2101.             entry->text_offset = section->offset;
  2102.             entry->text_reloc_size = section->nreloc * sizeof (struct relocation_info);
  2103.             entry->text_reloc_offset = section->reloff;
  2104.           }
  2105.           else if (!strncmp(SECT_DATA, section->sectname, sizeof section->sectname))
  2106.         if (entry->data_ordinal)
  2107.           fatal_with_file ("more than one __data section in ", entry);
  2108.         else
  2109.           {
  2110.             entry->data_ordinal = ordinal;
  2111.             entry->orig_data_address = section->addr;
  2112.             entry->data_size = section->size;
  2113.             entry->data_offset = section->offset;
  2114.             entry->data_reloc_size = section->nreloc * sizeof (struct relocation_info);
  2115.             entry->data_reloc_offset = section->reloff;
  2116.           }
  2117.           else if (!strncmp(SECT_BSS, section->sectname, sizeof section->sectname))
  2118.         if (entry->bss_ordinal)
  2119.           fatal_with_file ("more than one __bss section in ", entry);
  2120.         else
  2121.           {
  2122.             entry->bss_ordinal = ordinal;
  2123.             entry->orig_bss_address = section->addr;
  2124.             entry->bss_size = section->size;
  2125.           }
  2126.           else
  2127.         if (section->size != 0)
  2128.           fprintf (stderr, "%s: warning: unknown section `%.*s' in %s\n",
  2129.                progname, sizeof section->sectname, section->sectname,
  2130.                entry->filename);
  2131.         }
  2132.       break;
  2133.     case LC_SYMTAB:
  2134.       if (symtab_seen)
  2135.           fatal_with_file ("more than one LC_SYMTAB in ", entry);
  2136.       else
  2137.         {
  2138.           symtab_seen = 1;
  2139.           symtab_command = (struct symtab_command *) load_command;
  2140.           entry->syms_size = symtab_command->nsyms * sizeof (struct nlist);
  2141.           entry->syms_offset = symtab_command->symoff;
  2142.           entry->strs_size = symtab_command->strsize;
  2143.           entry->strs_offset = symtab_command->stroff;
  2144.         }
  2145.       break;
  2146. #ifdef LC_SYMSEG
  2147.     case LC_SYMSEG:
  2148.       if (symseg_seen)
  2149.         fatal_with_file ("more than one LC_SYMSEG in ", entry);
  2150.       else
  2151.         {
  2152.           symseg_seen = 1;
  2153.           symseg_command = (struct symseg_command *) load_command;
  2154.           entry->symseg_size = symseg_command->size;
  2155.           entry->symseg_offset = symseg_command->offset;
  2156.         }
  2157.       break;
  2158. #endif
  2159.     }
  2160.       load_command = (struct load_command *)
  2161.     ((char *) load_command + load_command->cmdsize);
  2162.     }
  2163.  
  2164.   free (hdrbuf);
  2165.  
  2166.   if (!symtab_seen)
  2167.     fprintf (stderr, "%s: no symbol table in %s\n", progname, entry->filename);
  2168. }
  2169. #endif
  2170.  
  2171. /* Read a file's header info into the proper place in the file_entry.
  2172.    DESC is the descriptor on which the file is open.
  2173.    ENTRY is the file's entry.
  2174.    Switch in the file_type to determine the appropriate actual
  2175.    header reading routine to call.  */
  2176.  
  2177. void
  2178. read_header (desc, entry)
  2179.      int desc;
  2180.      register struct file_entry *entry;
  2181. {
  2182.   if (!entry->file_type)
  2183.     deduce_file_type (desc, entry);
  2184.  
  2185.   switch (entry->file_type)
  2186.     {
  2187.     case IS_ARCHIVE:
  2188.     default:
  2189.       /* Should never happen. */
  2190.       abort ();
  2191.  
  2192. #ifdef A_OUT
  2193.     case IS_A_OUT:
  2194.       read_a_out_header (desc, entry);
  2195.       break;
  2196. #endif
  2197.  
  2198. #ifdef MACH_O
  2199.     case IS_MACH_O:
  2200.       read_mach_o_header (desc, entry);
  2201.       break;
  2202. #endif
  2203.     }
  2204.  
  2205.   entry->header_read_flag = 1;
  2206. }
  2207.  
  2208. #ifdef MACH_O
  2209. void translate_mach_o_symbols ();
  2210. #endif
  2211.  
  2212. /* Read the symbols of file ENTRY into core.
  2213.    Assume it is already open, on descriptor DESC.  */
  2214.  
  2215. void
  2216. read_entry_symbols (desc, entry)
  2217.      struct file_entry *entry;
  2218.      int desc;
  2219. {
  2220.   int str_size;
  2221.  
  2222.   if (!entry->header_read_flag)
  2223.     read_header (desc, entry);
  2224.  
  2225.   entry->symbols = (struct nlist *) xmalloc (entry->syms_size);
  2226.  
  2227.   lseek (desc, entry->syms_offset + entry->starting_offset, 0);
  2228.   if (entry->syms_size != read (desc, entry->symbols, entry->syms_size))
  2229.     fatal_with_file ("premature end of file in symbols of ", entry);
  2230.  
  2231. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2232.   fix_symbol_byte_order(entry->symbols, entry->syms_size);
  2233. #endif
  2234.  
  2235. #ifdef MACH_O
  2236.   if (entry->file_type == IS_MACH_O)
  2237.     translate_mach_o_symbols (entry);
  2238. #endif
  2239. }
  2240.  
  2241. /* Read the string table of file ENTRY into core.
  2242.    Assume it is already open, on descriptor DESC.  */
  2243.  
  2244. void
  2245. read_entry_strings (desc, entry)
  2246.      struct file_entry *entry;
  2247.      int desc;
  2248. {
  2249.   int buffer;
  2250.  
  2251.   if (!entry->header_read_flag)
  2252.     read_header (desc, entry);
  2253.  
  2254.   lseek (desc, entry->strs_offset + entry->starting_offset, 0);
  2255.   if (entry->strs_size != read (desc, entry->strings, entry->strs_size))
  2256.     fatal_with_file ("premature end of file in strings of ", entry);
  2257. }
  2258.  
  2259. /* Read in the symbols of all input files.  */
  2260.  
  2261. void read_file_symbols (), read_entry_symbols (), read_entry_strings ();
  2262. void enter_file_symbols (), enter_global_ref (), search_library ();
  2263.  
  2264. void
  2265. load_symbols ()
  2266. {
  2267.   register int i;
  2268.  
  2269.   if (trace_files) fprintf (stderr, "Loading symbols:\n\n");
  2270.  
  2271.   for (i = 0; i < number_of_files; i++)
  2272.     {
  2273.       register struct file_entry *entry = &file_table[i];
  2274.       read_file_symbols (entry);
  2275.     }
  2276.  
  2277.   if (trace_files) fprintf (stderr, "\n");
  2278. }
  2279.  
  2280. /* If ENTRY is a rel file, read its symbol and string sections into core.
  2281.    If it is a library, search it and load the appropriate members
  2282.    (which means calling this function recursively on those members).  */
  2283.  
  2284. void
  2285. read_file_symbols (entry)
  2286.      register struct file_entry *entry;
  2287. {
  2288.   register int desc;
  2289.  
  2290.   desc = file_open (entry);
  2291.  
  2292.   if (!entry->file_type)
  2293.     deduce_file_type (desc, entry);
  2294.  
  2295.   if (entry->file_type == IS_ARCHIVE)
  2296.     {
  2297.       entry->library_flag = 1;
  2298.       search_library (desc, entry);
  2299.     }
  2300.   else
  2301.     {
  2302.       read_entry_symbols (desc, entry);
  2303.       entry->strings = (char *) alloca (entry->strs_size);
  2304.       read_entry_strings (desc, entry);
  2305.       enter_file_symbols (entry);
  2306.       entry->strings = 0;
  2307.     }
  2308.  
  2309.   file_close ();
  2310. }
  2311.  
  2312. /* Enter the external symbol defs and refs of ENTRY in the hash table.  */
  2313.  
  2314. void
  2315. enter_file_symbols (entry)
  2316.      struct file_entry *entry;
  2317. {
  2318.   register struct nlist
  2319.     *p,
  2320.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2321.  
  2322.   if (trace_files) prline_file_name (entry, stderr);
  2323.  
  2324.   for (p = entry->symbols; p < end; p++)
  2325.     {
  2326.       if (p->n_type == (N_SETV | N_EXT)) continue;
  2327.       if (set_element_prefixes
  2328.       && set_element_prefixed_p (p->n_un.n_strx + entry->strings))
  2329.     p->n_type += (N_SETA - N_ABS);
  2330.  
  2331.       if (SET_ELEMENT_P (p->n_type))
  2332.     {
  2333.       set_symbol_count++;
  2334.       if (output_style != OUTPUT_RELOCATABLE)
  2335.         enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2336.     }
  2337.       else if (p->n_type == N_WARNING)
  2338.     {
  2339.       char *name = p->n_un.n_strx + entry->strings;
  2340.  
  2341.       /* Grab the next entry.  */
  2342.       p++;
  2343.       if (p->n_type != (N_UNDF | N_EXT))
  2344.         {
  2345.           fprintf (stderr, "%s: Warning symbol found in %s without external reference following.\n",
  2346.                progname, entry->filename);
  2347.           make_executable = 0;
  2348.           p--;        /* Process normally.  */
  2349.         }
  2350.       else
  2351.         {
  2352.           symbol *sp;
  2353.           char *sname = p->n_un.n_strx + entry->strings;
  2354.           /* Deal with the warning symbol.  */
  2355.           enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2356.           sp = getsym (sname);
  2357.           sp->warning = (char *) xmalloc (strlen(name) + 1);
  2358.           strcpy (sp->warning, name);
  2359.           warning_count++;
  2360.         }
  2361.     }
  2362.       else if (p->n_type & N_EXT)
  2363.     enter_global_ref (p, p->n_un.n_strx + entry->strings, entry);
  2364.       else if (p->n_un.n_strx && !(p->n_type & (N_STAB | N_EXT)))
  2365.     {
  2366.       if ((p->n_un.n_strx + entry->strings)[0] != LPREFIX)
  2367.         non_L_local_sym_count++;
  2368.       local_sym_count++;
  2369.     }
  2370.       else debugger_sym_count++;
  2371.     }
  2372.  
  2373.    /* Count one for the local symbol that we generate,
  2374.       whose name is the file's name (usually) and whose address
  2375.       is the start of the file's text.  */
  2376.  
  2377.   local_sym_count++;
  2378.   non_L_local_sym_count++;
  2379. }
  2380.  
  2381. /* Enter one global symbol in the hash table.
  2382.    NLIST_P points to the `struct nlist' read from the file
  2383.    that describes the global symbol.  NAME is the symbol's name.
  2384.    ENTRY is the file entry for the file the symbol comes from.
  2385.  
  2386.    The `struct nlist' is modified by placing it on a chain of
  2387.    all such structs that refer to the same global symbol.
  2388.    This chain starts in the `refs' field of the symbol table entry
  2389.    and is chained through the `n_name'.  */
  2390.  
  2391. void
  2392. enter_global_ref (nlist_p, name, entry)
  2393.      register struct nlist *nlist_p;
  2394.      char *name;
  2395.      struct file_entry *entry;
  2396. {
  2397.   register symbol *sp = getsym (name);
  2398.   register int type = nlist_p->n_type;
  2399.   int oldref = sp->referenced;
  2400.   int olddef = sp->defined;
  2401.  
  2402.   nlist_p->n_un.n_name = (char *) sp->refs;
  2403.   sp->refs = nlist_p;
  2404.  
  2405.   sp->referenced = 1;
  2406.   if (type != (N_UNDF | N_EXT) || nlist_p->n_value)
  2407.     {
  2408.       if (!sp->defined || sp->defined == (N_UNDF | N_EXT))
  2409.     sp->defined = type;
  2410.  
  2411.       if (oldref && !olddef)
  2412.     /* It used to be undefined and we're defining it.  */
  2413.     undefined_global_sym_count--;
  2414.  
  2415.       if (!olddef && type == (N_UNDF | N_EXT) && nlist_p->n_value)
  2416.     {
  2417.       /* First definition and it's common.  */
  2418.       common_defined_global_count++;
  2419.       sp->max_common_size = nlist_p->n_value;
  2420.     }
  2421.       else if (olddef && sp->max_common_size && type != (N_UNDF | N_EXT))
  2422.     {
  2423.       /* It used to be common and we're defining it as
  2424.          something else.  */
  2425.       common_defined_global_count--;
  2426.       sp->max_common_size = 0;
  2427.     }
  2428.       else if (olddef && sp->max_common_size && type == (N_UNDF | N_EXT)
  2429.       && sp->max_common_size < nlist_p->n_value)
  2430.     /* It used to be common and this is a new common entry to
  2431.        which we need to pay attention.  */
  2432.     sp->max_common_size = nlist_p->n_value;
  2433.  
  2434.       /* Are we defining it as a set element?  */
  2435.       if (SET_ELEMENT_P (type)
  2436.       && (!olddef || (olddef && sp->max_common_size)))
  2437.     set_vector_count++;
  2438.       /* As an indirection?  */
  2439.       else if (type == (N_INDR | N_EXT))
  2440.     {
  2441.       /* Indirect symbols value should be modified to point
  2442.          a symbol being equivalenced to. */
  2443.       nlist_p->n_value
  2444. #ifndef NeXT
  2445.         = (unsigned int) getsym ((nlist_p + 1)->n_un.n_strx
  2446.                      + entry->strings);
  2447. #else
  2448.         /* NeXT also has indirection but they do it weirdly. */
  2449.         = (unsigned int) getsym (nlist_p->n_value + entry->strings);
  2450. #endif
  2451.       if ((symbol *) nlist_p->n_value == sp)
  2452.         {
  2453.           /* Somebody redefined a symbol to be itself.  */
  2454.           fprintf (stderr, "%s: Symbol %s indirected to itself.\n",
  2455.                entry->filename, name);
  2456.           /* Rewrite this symbol as being a global text symbol
  2457.          with value 0.  */
  2458.           nlist_p->n_type = sp->defined = N_TEXT | N_EXT;
  2459.           nlist_p->n_value = 0;
  2460.           /* Don't make the output executable.  */
  2461.           make_executable = 0;
  2462.         }
  2463.       else
  2464.         global_indirect_count++;
  2465.     }
  2466.     }
  2467.   else
  2468.     if (!oldref)
  2469. #ifndef DOLLAR_KLUDGE
  2470.       undefined_global_sym_count++;
  2471. #else
  2472.       {
  2473.     if (entry->superfile && type == (N_UNDF | N_EXT) && name[1] == '$')
  2474.       {
  2475.         /* This is an (ISI?) $-conditional; skip it */
  2476.         sp->referenced = 0;
  2477.         if (sp->trace)
  2478.           {
  2479.         fprintf (stderr, "symbol %s is a $-conditional ignored in ", sp->name);
  2480.         print_file_name (entry, stderr);
  2481.         fprintf (stderr, "\n");
  2482.           }
  2483.         return;
  2484.       }
  2485.     else
  2486.       undefined_global_sym_count++;
  2487.       }
  2488. #endif
  2489.  
  2490.   if (sp == end_symbol && entry->just_syms_flag && !T_flag_specified)
  2491.     text_start = nlist_p->n_value;
  2492.  
  2493.   if (sp->trace)
  2494.     {
  2495.       register char *reftype;
  2496.       switch (type & ~N_EXT)
  2497.     {
  2498.     case N_UNDF:
  2499.       if (nlist_p->n_value)
  2500.         reftype = "defined as common";
  2501.       else reftype = "referenced";
  2502.       break;
  2503.  
  2504.     case N_ABS:
  2505.       reftype = "defined as absolute";
  2506.       break;
  2507.  
  2508.     case N_TEXT:
  2509.       reftype = "defined in text section";
  2510.       break;
  2511.  
  2512.     case N_DATA:
  2513.       reftype = "defined in data section";
  2514.       break;
  2515.  
  2516.     case N_BSS:
  2517.       reftype = "defined in BSS section";
  2518.       break;
  2519.  
  2520.     case N_SETT:
  2521.       reftype = "is a text set element";
  2522.       break;
  2523.  
  2524.     case N_SETD:
  2525.       reftype = "is a data set element";
  2526.       break;
  2527.  
  2528.     case N_SETB:
  2529.       reftype = "is a BSS set element";
  2530.       break;
  2531.  
  2532.     case N_SETA:
  2533.       reftype = "is an absolute set element";
  2534.       break;
  2535.  
  2536.     case N_SETV:
  2537.       reftype = "defined in data section as vector";
  2538.       break;
  2539.  
  2540.     case N_INDR:
  2541.       reftype = (char *) alloca (23 + strlen (((symbol *) nlist_p->n_value)->name));
  2542.       sprintf (reftype, "defined equivalent to %s",
  2543.            ((symbol *) nlist_p->n_value)->name);
  2544.       break;
  2545.  
  2546. #ifdef sequent
  2547.     case N_SHUNDF:
  2548.       reftype = "shared undf";
  2549.       break;
  2550.  
  2551. /* These conflict with cases above.
  2552.     case N_SHDATA:
  2553.       reftype = "shared data";
  2554.       break;
  2555.  
  2556.     case N_SHBSS:
  2557.       reftype = "shared BSS";
  2558.       break;
  2559. */
  2560. #endif
  2561.  
  2562.     default:
  2563.       reftype = "I don't know this type";
  2564.       break;
  2565.     }
  2566.  
  2567.       fprintf (stderr, "symbol %s %s in ", sp->name, reftype);
  2568.       print_file_name (entry, stderr);
  2569.       fprintf (stderr, "\n");
  2570.     }
  2571. }
  2572.  
  2573. /* This return 0 if the given file entry's symbol table does *not*
  2574.    contain the nlist point entry, and it returns the files entry
  2575.    pointer (cast to unsigned long) if it does. */
  2576.  
  2577. unsigned long
  2578. contains_symbol (entry, n_ptr)
  2579.      struct file_entry *entry;
  2580.      register struct nlist *n_ptr;
  2581. {
  2582.   if (n_ptr >= entry->symbols &&
  2583.       n_ptr < (entry->symbols
  2584.            + (entry->syms_size / sizeof (struct nlist))))
  2585.     return (unsigned long) entry;
  2586.   return 0;
  2587. }
  2588.  
  2589.  
  2590. /* Searching libraries */
  2591.  
  2592. struct file_entry *decode_library_subfile ();
  2593. void linear_library (), symdef_library ();
  2594.  
  2595. /* Search the library ENTRY, already open on descriptor DESC.
  2596.    This means deciding which library members to load,
  2597.    making a chain of `struct file_entry' for those members,
  2598.    and entering their global symbols in the hash table.  */
  2599.  
  2600. void
  2601. search_library (desc, entry)
  2602.      int desc;
  2603.      struct file_entry *entry;
  2604. {
  2605.   int member_length;
  2606.   register char *name;
  2607.   register struct file_entry *subentry;
  2608.  
  2609.   if (!undefined_global_sym_count) return;
  2610.  
  2611.   /* Examine its first member, which starts SARMAG bytes in.  */
  2612.   subentry = decode_library_subfile (desc, entry, SARMAG, &member_length);
  2613.   if (!subentry) return;
  2614.  
  2615.   name = subentry->filename;
  2616.   free (subentry);
  2617.  
  2618.   /* Search via __.SYMDEF if that exists, else linearly.  */
  2619.  
  2620.   if (!strcmp (name, "__.SYMDEF"))
  2621.     symdef_library (desc, entry, member_length);
  2622.   else
  2623.     linear_library (desc, entry);
  2624. }
  2625.  
  2626. /* Construct and return a file_entry for a library member.
  2627.    The library's file_entry is library_entry, and the library is open on DESC.
  2628.    SUBFILE_OFFSET is the byte index in the library of this member's header.
  2629.    We store the length of the member into *LENGTH_LOC.  */
  2630.  
  2631. struct file_entry *
  2632. decode_library_subfile (desc, library_entry, subfile_offset, length_loc)
  2633.      int desc;
  2634.      struct file_entry *library_entry;
  2635.      int subfile_offset;
  2636.      int *length_loc;
  2637. {
  2638.   int bytes_read;
  2639.   register int namelen;
  2640.   int member_length;
  2641.   register char *name;
  2642.   struct ar_hdr hdr1;
  2643.   register struct file_entry *subentry;
  2644.  
  2645.   lseek (desc, subfile_offset, 0);
  2646.  
  2647.   bytes_read = read (desc, &hdr1, sizeof hdr1);
  2648.   if (!bytes_read)
  2649.     return 0;        /* end of archive */
  2650.  
  2651.   if (sizeof hdr1 != bytes_read)
  2652.     fatal_with_file ("malformed library archive ", library_entry);
  2653.  
  2654.   if (sscanf (hdr1.ar_size, "%d", &member_length) != 1)
  2655.     fatal_with_file ("malformatted header of archive member in ", library_entry);
  2656.  
  2657.   subentry = (struct file_entry *) xmalloc (sizeof (struct file_entry));
  2658.   bzero (subentry, sizeof (struct file_entry));
  2659.  
  2660.   for (namelen = 0;
  2661.        namelen < sizeof hdr1.ar_name
  2662.        && hdr1.ar_name[namelen] != 0 && hdr1.ar_name[namelen] != ' '
  2663.        && hdr1.ar_name[namelen] != '/';
  2664.        namelen++);
  2665.  
  2666.   name = (char *) xmalloc (namelen+1);
  2667.   strncpy (name, hdr1.ar_name, namelen);
  2668.   name[namelen] = 0;
  2669.  
  2670.   subentry->filename = name;
  2671.   subentry->local_sym_name = name;
  2672.   subentry->symbols = 0;
  2673.   subentry->strings = 0;
  2674.   subentry->subfiles = 0;
  2675.   subentry->starting_offset = subfile_offset + sizeof hdr1;
  2676.   subentry->superfile = library_entry;
  2677.   subentry->library_flag = 0;
  2678.   subentry->header_read_flag = 0;
  2679.   subentry->just_syms_flag = 0;
  2680.   subentry->chain = 0;
  2681.   subentry->total_size = member_length;
  2682.  
  2683.   (*length_loc) = member_length;
  2684.  
  2685.   return subentry;
  2686. }
  2687.  
  2688. int subfile_wanted_p ();
  2689.  
  2690. /* Search a library that has a __.SYMDEF member.
  2691.    DESC is a descriptor on which the library is open.
  2692.      The file pointer is assumed to point at the __.SYMDEF data.
  2693.    ENTRY is the library's file_entry.
  2694.    MEMBER_LENGTH is the length of the __.SYMDEF data.  */
  2695.  
  2696. void
  2697. symdef_library (desc, entry, member_length)
  2698.      int desc;
  2699.      struct file_entry *entry;
  2700.      int member_length;
  2701. {
  2702.   int *symdef_data = (int *) xmalloc (member_length);
  2703.   register struct symdef *symdef_base;
  2704.   char *sym_name_base;
  2705.   int number_of_symdefs;
  2706.   int length_of_strings;
  2707.   int not_finished;
  2708.   int bytes_read;
  2709.   register int i;
  2710.   struct file_entry *prev = 0;
  2711.   int prev_offset = 0;
  2712.  
  2713.   bytes_read = read (desc, symdef_data, member_length);
  2714.   if (bytes_read != member_length)
  2715.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2716. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2717.   fix_byte_order(symdef_data, sizeof(*symdef_data));
  2718. #endif
  2719.   number_of_symdefs = *symdef_data / sizeof (struct symdef);
  2720.   if (number_of_symdefs < 0 ||
  2721.        number_of_symdefs * sizeof (struct symdef) + 2 * sizeof (int) > member_length)
  2722.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2723.  
  2724.   symdef_base = (struct symdef *) (symdef_data + 1);
  2725. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  2726.   for (i = 0; i < number_of_symdefs; ++i)
  2727.     {
  2728.       fix_byte_order(&symdef_base[i].symbol_name_string_index, sizeof(int));
  2729.       fix_byte_order(&symdef_base[i].library_member_offset, sizeof(int));
  2730.     }
  2731.   fix_byte_order(symdef_base + number_of_symdefs, sizeof(int));
  2732. #endif
  2733.   length_of_strings = *(int *) (symdef_base + number_of_symdefs);
  2734.  
  2735.   if (length_of_strings < 0
  2736.       || number_of_symdefs * sizeof (struct symdef) + length_of_strings
  2737.       + 2 * sizeof (int) != member_length)
  2738.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2739.  
  2740.   sym_name_base = sizeof (int) + (char *) (symdef_base + number_of_symdefs);
  2741.  
  2742.   /* Check all the string indexes for validity.  */
  2743.  
  2744.   for (i = 0; i < number_of_symdefs; i++)
  2745.     {
  2746.       register int index = symdef_base[i].symbol_name_string_index;
  2747.       if (index < 0 || index >= length_of_strings
  2748.       || (index && *(sym_name_base + index - 1)))
  2749.     fatal_with_file ("malformatted __.SYMDEF in ", entry);
  2750.     }
  2751.  
  2752.   /* Search the symdef data for members to load.
  2753.      Do this until one whole pass finds nothing to load.  */
  2754.  
  2755.   not_finished = 1;
  2756.   while (not_finished)
  2757.     {
  2758.       not_finished = 0;
  2759.  
  2760.       /* Scan all the symbols mentioned in the symdef for ones that we need.
  2761.      Load the library members that contain such symbols.  */
  2762.  
  2763.       for (i = 0;
  2764.        (i < number_of_symdefs
  2765.         && (undefined_global_sym_count || common_defined_global_count));
  2766.        i++)
  2767.     if (symdef_base[i].symbol_name_string_index >= 0)
  2768.       {
  2769.         register symbol *sp;
  2770.  
  2771.         sp = getsym_soft (sym_name_base
  2772.                   + symdef_base[i].symbol_name_string_index);
  2773.  
  2774.         /* If we find a symbol that appears to be needed, think carefully
  2775.            about the archive member that the symbol is in.  */
  2776.  
  2777.         if (sp && ((sp->referenced && !sp->defined)
  2778.                || (sp->defined && sp->max_common_size)))
  2779.           {
  2780.         int junk;
  2781.         register int j;
  2782.         register int offset = symdef_base[i].library_member_offset;
  2783.         struct file_entry *subentry;
  2784.  
  2785.         /* Don't think carefully about any archive member
  2786.            more than once in a given pass.  */
  2787.  
  2788.         if (prev_offset == offset)
  2789.           continue;
  2790.         prev_offset = offset;
  2791.  
  2792.         /* Read the symbol table of the archive member.  */
  2793.  
  2794.         subentry = decode_library_subfile (desc, entry, offset, &junk);
  2795.         if (subentry == 0)
  2796.           fatal ("invalid offset for %s in symbol table of %s",
  2797.              sym_name_base
  2798.              + symdef_base[i].symbol_name_string_index,
  2799.              entry->filename);
  2800.         read_entry_symbols (desc, subentry);
  2801.         subentry->strings = xmalloc (subentry->strs_size);
  2802.         read_entry_strings (desc, subentry);
  2803.  
  2804.         /* Now scan the symbol table and decide whether to load.  */
  2805.  
  2806.         if (!subfile_wanted_p (subentry))
  2807.           {
  2808.             free (subentry->symbols);
  2809.             free (subentry->strings);
  2810.             free (subentry);
  2811.           }
  2812.         else
  2813.           {
  2814.             /* This member is needed; load it.
  2815.                Since we are loading something on this pass,
  2816.                we must make another pass through the symdef data.  */
  2817.  
  2818.             not_finished = 1;
  2819.  
  2820.             enter_file_symbols (subentry);
  2821.  
  2822.             if (prev)
  2823.               prev->chain = subentry;
  2824.             else entry->subfiles = subentry;
  2825.             prev = subentry;
  2826.  
  2827.             /* Clear out this member's symbols from the symdef data
  2828.                so that following passes won't waste time on them.  */
  2829.  
  2830.             for (j = 0; j < number_of_symdefs; j++)
  2831.               {
  2832.             if (symdef_base[j].library_member_offset == offset)
  2833.               symdef_base[j].symbol_name_string_index = -1;
  2834.               }
  2835.  
  2836.             /* We'll read the strings again if we need them again.  */
  2837.             free (subentry->strings);
  2838.             subentry->strings = 0;
  2839.           }
  2840.           }
  2841.       }
  2842.     }
  2843.  
  2844.   free (symdef_data);
  2845. }
  2846.  
  2847.  
  2848. /* Handle a subentry for a file with no __.SYMDEF. */
  2849.  
  2850. process_subentry (desc, subentry, entry, prev_addr)
  2851.      int desc;
  2852.      register struct file_entry *subentry;
  2853.      struct file_entry **prev_addr, *entry;
  2854. {
  2855.   read_entry_symbols (desc, subentry);
  2856.   subentry->strings = (char *) alloca (subentry->strs_size);
  2857.   read_entry_strings (desc, subentry);
  2858.  
  2859.   if (!subfile_wanted_p (subentry))
  2860.     {
  2861.       free (subentry->symbols);
  2862.       free (subentry);
  2863.     }
  2864.   else
  2865.     {
  2866.       enter_file_symbols (subentry);
  2867.  
  2868.       if (*prev_addr)
  2869.     (*prev_addr)->chain = subentry;
  2870.       else
  2871.     entry->subfiles = subentry;
  2872.       *prev_addr = subentry;
  2873.       subentry->strings = 0; /* Since space will dissapear on return */
  2874.     }
  2875. }
  2876.  
  2877. /* Search a library that has no __.SYMDEF.
  2878.    ENTRY is the library's file_entry.
  2879.    DESC is the descriptor it is open on.  */
  2880.  
  2881. void
  2882. linear_library (desc, entry)
  2883.      int desc;
  2884.      struct file_entry *entry;
  2885. {
  2886.   struct file_entry *prev = 0;
  2887.   register int this_subfile_offset = SARMAG;
  2888.  
  2889.   while (undefined_global_sym_count || common_defined_global_count)
  2890.     {
  2891.       int member_length;
  2892.       register struct file_entry *subentry;
  2893.  
  2894.       subentry = decode_library_subfile (desc, entry, this_subfile_offset,
  2895.                      &member_length);
  2896.       if (!subentry) return;
  2897.  
  2898.       process_subentry (desc, subentry, entry, &prev);
  2899.       this_subfile_offset += member_length + sizeof (struct ar_hdr);
  2900.       if (this_subfile_offset & 1) this_subfile_offset++;
  2901.     }
  2902. }
  2903.  
  2904. /* ENTRY is an entry for a library member.
  2905.    Its symbols have been read into core, but not entered.
  2906.    Return nonzero if we ought to load this member.  */
  2907.  
  2908. int
  2909. subfile_wanted_p (entry)
  2910.      struct file_entry *entry;
  2911. {
  2912.   register struct nlist *p;
  2913.   register struct nlist *end
  2914.     = entry->symbols + entry->syms_size / sizeof (struct nlist);
  2915. #ifdef DOLLAR_KLUDGE
  2916.   register int dollar_cond = 0;
  2917. #endif
  2918.  
  2919.   for (p = entry->symbols; p < end; p++)
  2920.     {
  2921.       register int type = p->n_type;
  2922.       register char *name = p->n_un.n_strx + entry->strings;
  2923.  
  2924.       /* If the symbol has an interesting definition, we could
  2925.      potentially want it.  */
  2926.       if (type & N_EXT
  2927.       && (type != (N_UNDF | N_EXT) || p->n_value
  2928.  
  2929. #ifdef DOLLAR_KLUDGE
  2930.            || name[1] == '$'
  2931. #endif
  2932.           )
  2933.       && !SET_ELEMENT_P (type)
  2934.       && !set_element_prefixed_p (name))
  2935.     {
  2936.       register symbol *sp = getsym_soft (name);
  2937.  
  2938. #ifdef DOLLAR_KLUDGE
  2939.       if (name[1] == '$')
  2940.         {
  2941.           sp = getsym_soft (&name[2]);
  2942.           dollar_cond = 1;
  2943.           if (!sp) continue;
  2944.           if (sp->referenced)
  2945.         {
  2946.           if (write_map)
  2947.             {
  2948.               print_file_name (entry, stdout);
  2949.               fprintf (stdout, " needed due to $-conditional %s\n", name);
  2950.             }
  2951.           return 1;
  2952.         }
  2953.           continue;
  2954.         }
  2955. #endif
  2956.  
  2957.       /* If this symbol has not been hashed, we can't be looking for it. */
  2958.  
  2959.       if (!sp) continue;
  2960.  
  2961.       if ((sp->referenced && !sp->defined)
  2962.           /* NB.  This needs to be changed so that, e.g., "int pipe;" won't import
  2963.          pipe() from the library.  But the bug fix kingdon made was wrong.  */
  2964.           || (sp->defined && sp->max_common_size))
  2965.         {
  2966.           /* This is a symbol we are looking for.  It is either
  2967.              not yet defined or defined as a common.  */
  2968. #ifdef DOLLAR_KLUDGE
  2969.           if (dollar_cond) continue;
  2970. #endif
  2971.           if (type == (N_UNDF | N_EXT))
  2972.         {
  2973.           /* Symbol being defined as common.
  2974.              Remember this, but don't load subfile just for this.  */
  2975.  
  2976.           /* If it didn't used to be common, up the count of
  2977.              common symbols.  */
  2978.           if (!sp->max_common_size)
  2979.             common_defined_global_count++;
  2980.  
  2981.           if (sp->max_common_size < p->n_value)
  2982.             sp->max_common_size = p->n_value;
  2983.           if (!sp->defined)
  2984.             undefined_global_sym_count--;
  2985.           sp->defined = 1;
  2986.           continue;
  2987.         }
  2988.  
  2989.           if (write_map)
  2990.         {
  2991.           print_file_name (entry, stdout);
  2992.           fprintf (stdout, " needed due to %s\n", sp->name);
  2993.         }
  2994.           return 1;
  2995.         }
  2996.     }
  2997.     }
  2998.  
  2999.   return 0;
  3000. }
  3001.  
  3002. void consider_file_section_lengths (), relocate_file_addresses ();
  3003.  
  3004. /* Having entered all the global symbols and found the sizes of sections
  3005.    of all files to be linked, make all appropriate deductions from this data.
  3006.  
  3007.    We propagate global symbol values from definitions to references.
  3008.    We compute the layout of the output file and where each input file's
  3009.    contents fit into it.  */
  3010.  
  3011. void
  3012. digest_symbols ()
  3013. {
  3014.   register int i;
  3015.   int setv_fill_count;
  3016.  
  3017.   if (trace_files)
  3018.     fprintf (stderr, "Digesting symbol information:\n\n");
  3019.  
  3020.   /* Initialize the text_start address; this depends on the output file formats.  */
  3021.  
  3022.   initialize_text_start ();
  3023.  
  3024.   text_size = text_header_size;
  3025.  
  3026.   /* Compute total size of sections */
  3027.  
  3028.   each_file (consider_file_section_lengths, 0);
  3029.  
  3030.   /* If necessary, pad text section to full page in the file.
  3031.      Include the padding in the text segment size.  */
  3032.  
  3033.   if (output_style == OUTPUT_READONLY_TEXT || output_style == OUTPUT_DEMAND_PAGED)
  3034.     {
  3035.       text_pad = ((text_size + page_size - 1) & (- page_size)) - text_size;
  3036.       text_size += text_pad;
  3037.     }
  3038.  
  3039.   /* Now that the text_size is known, initialize the data start address;
  3040.      this depends on text_size as well as the output file format.  */
  3041.  
  3042.   initialize_data_start ();
  3043.  
  3044.   /* Make sure bss starts out aligned as much as anyone can want.  */
  3045.   {
  3046.     int new_data_size = (data_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  3047.  
  3048.     data_pad += new_data_size - data_size;
  3049.     data_size = new_data_size;
  3050.   }
  3051.  
  3052.   /* Set up the set element vector */
  3053.  
  3054.   if (output_style != OUTPUT_RELOCATABLE)
  3055.     {
  3056.       /* The set sector size is the number of set elements + a word
  3057.          for each symbol for the length word at the beginning of the
  3058.      vector, plus a word for each symbol for a zero at the end of
  3059.      the vector (for incremental linking).  */
  3060.       set_sect_size
  3061.     = (2 * set_symbol_count + set_vector_count) * sizeof (unsigned long);
  3062.       set_sect_start = data_start + data_size;
  3063.       data_size += set_sect_size;
  3064.       set_vectors = (unsigned long *) xmalloc (set_sect_size);
  3065.       setv_fill_count = 0;
  3066.     }
  3067.  
  3068.   /* Compute start addresses of each file's sections and symbols.  */
  3069.  
  3070.   each_full_file (relocate_file_addresses, 0);
  3071.  
  3072.   /* Now, for each symbol, verify that it is defined globally at most once.
  3073.      Put the global value into the symbol entry.
  3074.      Common symbols are allocated here, in the BSS section.
  3075.      Each defined symbol is given a '->defined' field
  3076.       which is the correct N_ code for its definition,
  3077.       except in the case of common symbols with -r.
  3078.      Then make all the references point at the symbol entry
  3079.      instead of being chained together. */
  3080.  
  3081.   defined_global_sym_count = 0;
  3082.  
  3083.   for (i = 0; i < TABSIZE; i++)
  3084.     {
  3085.       register symbol *sp;
  3086.       for (sp = symtab[i]; sp; sp = sp->link)
  3087.     {
  3088.       /* For each symbol */
  3089.       register struct nlist *p, *next;
  3090.       int defs = 0, com = sp->max_common_size;
  3091.       struct nlist *first_definition;
  3092.       for (p = sp->refs; p; p = next)
  3093.         {
  3094.           register int type = p->n_type;
  3095.  
  3096.           if (SET_ELEMENT_P (type))
  3097.         {
  3098.           if (output_style == OUTPUT_RELOCATABLE)
  3099.             fatal ("internal: global ref to set element with -r");
  3100.           if (!defs++)
  3101.             {
  3102.               sp->value = set_sect_start
  3103.             + setv_fill_count++ * sizeof (unsigned long);
  3104.               sp->defined = N_SETV | N_EXT;
  3105.               first_definition = p;
  3106.             }
  3107.           else if ((sp->defined & ~N_EXT) != N_SETV)
  3108.             {
  3109.               sp->multiply_defined = 1;
  3110.               multiple_def_count++;
  3111.             }
  3112.           set_vectors[setv_fill_count++] = p->n_value;
  3113.         }
  3114.           else if ((type & N_EXT) && type != (N_UNDF | N_EXT))
  3115.         {
  3116.           /* non-common definition */
  3117.           if (defs++ && sp->value != p->n_value)
  3118.             {
  3119.               sp->multiply_defined = 1;
  3120.               multiple_def_count++;
  3121.             }
  3122.           sp->value = p->n_value;
  3123.           sp->defined = type;
  3124.           first_definition = p;
  3125.         }
  3126.           next = (struct nlist *) p->n_un.n_name;
  3127.           p->n_un.n_name = (char *) sp;
  3128.         }
  3129.       /* Allocate as common if defined as common and not defined for real */
  3130.       if (com && !defs)
  3131.         {
  3132.           if (output_style != OUTPUT_RELOCATABLE || force_common_definition)
  3133.         {
  3134.           int align = sizeof (int);
  3135.  
  3136.           /* Round up to nearest sizeof (int).  I don't know
  3137.              whether this is necessary or not (given that
  3138.              alignment is taken care of later), but it's
  3139.              traditional, so I'll leave it in.  Note that if
  3140.              this size alignment is ever removed, ALIGN above
  3141.              will have to be initialized to 1 instead of
  3142.              sizeof (int).  */
  3143.  
  3144.           com = (com + sizeof (int) - 1) & (- sizeof (int));
  3145.  
  3146.           while (!(com & align))
  3147.             align <<= 1;
  3148.  
  3149.           align = align > MAX_ALIGNMENT ? MAX_ALIGNMENT : align;
  3150.  
  3151.           bss_size = ((((bss_size + data_size + data_start)
  3152.                   + (align - 1)) & (- align))
  3153.                   - data_size - data_start);
  3154.  
  3155.           sp->value = data_start + data_size + bss_size;
  3156.           sp->defined = N_BSS | N_EXT;
  3157.           bss_size += com;
  3158.           if (write_map)
  3159.             printf ("Allocating common %s: %x at %x\n",
  3160.                 sp->name, com, sp->value);
  3161.         }
  3162.           else
  3163.         {
  3164.           sp->defined = 0;
  3165.           undefined_global_sym_count++;
  3166.         }
  3167.         }
  3168.       /* Set length word at front of vector and zero byte at end.
  3169.          Reverse the vector itself to put it in file order.  */
  3170.       if ((sp->defined & ~N_EXT) == N_SETV)
  3171.         {
  3172.           unsigned long length_word_index
  3173.         = (sp->value - set_sect_start) / sizeof (unsigned long);
  3174.           unsigned long i, tmp;
  3175.  
  3176.           set_vectors[length_word_index]
  3177.         = setv_fill_count - 1 - length_word_index;
  3178.  
  3179.           /* Reverse the vector.  */
  3180.           for (i = 1;
  3181.            i < (setv_fill_count - length_word_index - 1) / 2 + 1;
  3182.            i++)
  3183.         {
  3184.           tmp = set_vectors[length_word_index + i];
  3185.           set_vectors[length_word_index + i]
  3186.             = set_vectors[setv_fill_count - i];
  3187.           set_vectors[setv_fill_count - i] = tmp;
  3188.         }
  3189.  
  3190.           set_vectors[setv_fill_count++] = 0;
  3191.         }
  3192.       if (sp->defined)
  3193.         defined_global_sym_count++;
  3194.     }
  3195.     }
  3196.  
  3197.   /* Make sure end of bss is aligned as much as anyone can want.  */
  3198.  
  3199.   bss_size = (bss_size + sizeof(double) - 1) & ~(sizeof(double)-1);
  3200.  
  3201.   /* Give values to _end and friends.  */
  3202.   {
  3203.     int end_value = data_start + data_size + bss_size;
  3204.     if (end_symbol)
  3205.       end_symbol->value = end_value;
  3206.     if (end_symbol_alt)
  3207.       end_symbol_alt->value = end_value;
  3208.   }
  3209.  
  3210.   {
  3211.     int etext_value = text_size + text_start;
  3212.     if (etext_symbol)
  3213.       etext_symbol->value = etext_value;
  3214.     if (etext_symbol_alt)
  3215.       etext_symbol_alt->value = etext_value;
  3216.   }
  3217.  
  3218.   {
  3219.     int edata_value = data_start + data_size;
  3220.     if (edata_symbol)
  3221.       edata_symbol->value = edata_value;
  3222.     if (edata_symbol_alt)
  3223.       edata_symbol_alt->value = edata_value;
  3224.   }
  3225.  
  3226.   /* Figure the data_pad now, so that it overlaps with the bss addresses.  */
  3227.  
  3228.   {
  3229.     /* The amount of data_pad that we are computing now.  This is the
  3230.        part which overlaps with bss.  What was computed previously
  3231.        goes before bss.  */
  3232.     int data_pad_additional = 0;
  3233.     
  3234.     if (specified_data_size && specified_data_size > data_size)
  3235.       data_pad_additional = specified_data_size - data_size;
  3236.  
  3237.     if (output_style == OUTPUT_DEMAND_PAGED)
  3238.       data_pad_additional =
  3239.     ((data_pad_additional + data_size + page_size - 1) & (- page_size)) - data_size;
  3240.  
  3241.     bss_size -= data_pad_additional;
  3242.     if (bss_size < 0) bss_size = 0;
  3243.  
  3244.     data_size += data_pad_additional;
  3245.  
  3246.     data_pad += data_pad_additional;
  3247.   }
  3248. }
  3249.  
  3250. /* Accumulate the section sizes of input file ENTRY
  3251.    into the section sizes of the output file.  */
  3252.  
  3253. void
  3254. consider_file_section_lengths (entry)
  3255.      register struct file_entry *entry;
  3256. {
  3257.   if (entry->just_syms_flag)
  3258.     return;
  3259.  
  3260.   entry->text_start_address = text_size;
  3261.   /* If there were any vectors, we need to chop them off */
  3262.   text_size += entry->text_size;
  3263.   entry->data_start_address = data_size;
  3264.   data_size += entry->data_size;
  3265.   entry->bss_start_address = bss_size;
  3266.   bss_size += entry->bss_size;
  3267.  
  3268.   text_reloc_size += entry->text_reloc_size;
  3269.   data_reloc_size += entry->data_reloc_size;
  3270. }
  3271.  
  3272. /* Determine where the sections of ENTRY go into the output file,
  3273.    whose total section sizes are already known.
  3274.    Also relocate the addresses of the file's local and debugger symbols.  */
  3275.  
  3276. void
  3277. relocate_file_addresses (entry)
  3278.      register struct file_entry *entry;
  3279. {
  3280.   entry->text_start_address += text_start;
  3281.  
  3282.   /* Note that `data_start' and `data_size' have not yet been adjusted
  3283.      for the portion of data_pad which overlaps with bss.  If they had
  3284.      been, we would get the wrong results here.  */
  3285.   entry->data_start_address += data_start;
  3286.   entry->bss_start_address += data_start + data_size;
  3287.  
  3288.   {
  3289.     register struct nlist *p;
  3290.     register struct nlist *end
  3291.       = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3292.  
  3293.     for (p = entry->symbols; p < end; p++)
  3294.       {
  3295.     /* If this belongs to a section, update it by the section's start address */
  3296.     register int type = p->n_type & ~N_EXT;
  3297.  
  3298.     switch (type)
  3299.       {
  3300.       case N_TEXT:
  3301.       case N_SETT:
  3302.         p->n_value += entry->text_start_address - entry->orig_text_address;
  3303.         break;
  3304.       case N_DATA:
  3305.       case N_SETV:
  3306.       case N_SETD:
  3307.         /* Data segment symbol.  Subtract the address of the
  3308.            data segment in the input file, and add the address
  3309.            of this input file's data segment in the output file.  */
  3310.         p->n_value +=
  3311.           entry->data_start_address - entry->orig_data_address;
  3312.         break;
  3313.       case N_BSS:
  3314.       case N_SETB:
  3315.         /* likewise for symbols with value in BSS.  */
  3316.         p->n_value += entry->bss_start_address - entry->orig_bss_address;
  3317.         break;
  3318.       }
  3319.       }
  3320.   }
  3321. }
  3322.  
  3323. void describe_file_sections (), list_file_locals ();
  3324.  
  3325. /* Print a complete or partial map of the output file.  */
  3326.  
  3327. void
  3328. print_symbols (outfile)
  3329.      FILE *outfile;
  3330. {
  3331.   register int i;
  3332.  
  3333.   fprintf (outfile, "\nFiles:\n\n");
  3334.  
  3335.   each_file (describe_file_sections, outfile);
  3336.  
  3337.   fprintf (outfile, "\nGlobal symbols:\n\n");
  3338.  
  3339.   for (i = 0; i < TABSIZE; i++)
  3340.     {
  3341.       register symbol *sp;
  3342.       for (sp = symtab[i]; sp; sp = sp->link)
  3343.     {
  3344.       if (sp->defined == 1)
  3345.         fprintf (outfile, "  %s: common, length 0x%x\n", sp->name, sp->max_common_size);
  3346.       if (sp->defined)
  3347.         fprintf (outfile, "  %s: 0x%x\n", sp->name, sp->value);
  3348.       else if (sp->referenced)
  3349.         fprintf (outfile, "  %s: undefined\n", sp->name);
  3350.     }
  3351.     }
  3352.  
  3353.   each_file (list_file_locals, outfile);
  3354. }
  3355.  
  3356. void
  3357. describe_file_sections (entry, outfile)
  3358.      struct file_entry *entry;
  3359.      FILE *outfile;
  3360. {
  3361.   fprintf (outfile, "  ");
  3362.   print_file_name (entry, outfile);
  3363.   if (entry->just_syms_flag)
  3364.     fprintf (outfile, " symbols only\n", 0);
  3365.   else
  3366.     fprintf (outfile, " text %x(%x), data %x(%x), bss %x(%x) hex\n",
  3367.          entry->text_start_address, entry->text_size,
  3368.          entry->data_start_address, entry->data_size,
  3369.          entry->bss_start_address, entry->bss_size);
  3370. }
  3371.  
  3372. void
  3373. list_file_locals (entry, outfile)
  3374.      struct file_entry *entry;
  3375.      FILE *outfile;
  3376. {
  3377.   register struct nlist
  3378.     *p,
  3379.     *end = entry->symbols + entry->syms_size / sizeof (struct nlist);
  3380.  
  3381.   entry->strings = (char *) alloca (entry->strs_size);
  3382.   read_entry_strings (file_open (entry), entry);
  3383.  
  3384.   fprintf (outfile, "\nLocal symbols of ");
  3385.   print_file_name (entry, outfile);
  3386.   fprintf (outfile, ":\n\n");
  3387.  
  3388.   for (p = entry->symbols; p < end; p++)
  3389.     /* If this is a definition,
  3390.        update it if necessary by this file's start address.  */
  3391.     if (!(p->n_type & (N_STAB | N_EXT)))
  3392.       fprintf (outfile, "  %s: 0x%x\n",
  3393.            entry->strings + p->n_un.n_strx, p->n_value);
  3394.  
  3395.   entry->strings = 0;        /* All done with them.  */
  3396. }
  3397.  
  3398.  
  3399. /* Static vars for do_warnings and subroutines of it */
  3400. int list_unresolved_refs;    /* List unresolved refs */
  3401. int list_warning_symbols;    /* List warning syms */
  3402. int list_multiple_defs;        /* List multiple definitions */
  3403.  
  3404. /*
  3405.  * Structure for communication between do_file_warnings and it's
  3406.  * helper routines.  Will in practice be an array of three of these:
  3407.  * 0) Current line, 1) Next line, 2) Source file info.
  3408.  */
  3409. struct line_debug_entry
  3410. {
  3411.   int line;
  3412.   char *filename;
  3413.   struct nlist *sym;
  3414. };
  3415.  
  3416. void qsort ();
  3417. /*
  3418.  * Helper routines for do_file_warnings.
  3419.  */
  3420.  
  3421. /* Return an integer less than, equal to, or greater than 0 as per the
  3422.    relation between the two relocation entries.  Used by qsort.  */
  3423.  
  3424. int
  3425. relocation_entries_relation (rel1, rel2)
  3426.      struct relocation_info *rel1, *rel2;
  3427. {
  3428.   return RELOC_ADDRESS(rel1) - RELOC_ADDRESS(rel2);
  3429. }
  3430.  
  3431. /* Moves to the next debugging symbol in the file.  USE_DATA_SYMBOLS
  3432.    determines the type of the debugging symbol to look for (DSLINE or
  3433.    SLINE).  STATE_POINTER keeps track of the old and new locatiosn in
  3434.    the file.  It assumes that state_pointer[1] is valid; ie
  3435.    that it.sym points into some entry in the symbol table.  If
  3436.    state_pointer[1].sym == 0, this routine should not be called.  */
  3437.  
  3438. int
  3439. next_debug_entry (use_data_symbols, state_pointer)
  3440.      register int use_data_symbols;
  3441.      /* Next must be passed by reference! */
  3442.      struct line_debug_entry state_pointer[3];
  3443. {
  3444.   register struct line_debug_entry
  3445.     *current = state_pointer,
  3446.     *next = state_pointer + 1,
  3447.     /* Used to store source file */
  3448.     *source = state_pointer + 2;
  3449.   struct file_entry *entry = (struct file_entry *) source->sym;
  3450.  
  3451.   current->sym = next->sym;
  3452.   current->line = next->line;
  3453.   current->filename = next->filename;
  3454.  
  3455.   while (++(next->sym) < (entry->symbols
  3456.               + entry->syms_size/sizeof (struct nlist)))
  3457.     {
  3458.       /* n_type is a char, and N_SOL, N_EINCL and N_BINCL are > 0x80, so
  3459.        * may look negative...therefore, must mask to low bits
  3460.        */
  3461.       switch (next->sym->n_type & 0xff)
  3462.     {
  3463.     case N_SLINE:
  3464.       if (use_data_symbols) continue;
  3465.       next->line = next->sym->n_desc;
  3466.       return 1;
  3467.     case N_DSLINE:
  3468.       if (!use_data_symbols) continue;
  3469.       next->line = next->sym->n_desc;
  3470.       return 1;
  3471. #ifdef HAVE_SUN_STABS
  3472.     case N_EINCL:
  3473.       next->filename = source->filename;
  3474.       continue;
  3475. #endif
  3476.     case N_SO:
  3477.       source->filename = next->sym->n_un.n_strx + entry->strings;
  3478.       source->line++;
  3479. #ifdef HAVE_SUN_STABS
  3480.     case N_BINCL:
  3481. #endif
  3482.     case N_SOL:
  3483.       next->filename
  3484.         = next->sym->n_un.n_strx + entry->strings;
  3485.     default:
  3486.       continue;
  3487.     }
  3488.     }
  3489.   next->sym = (struct nlist *) 0;
  3490.   return 0;
  3491. }
  3492.  
  3493. /* Create a structure to save the state of a scan through the debug
  3494.    symbols.  USE_DATA_SYMBOLS is set if we should be scanning for
  3495.    DSLINE's instead of SLINE's.  entry is the file entry which points
  3496.    at the symbols to use.  */
  3497.  
  3498. struct line_debug_entry *
  3499. init_debug_scan (use_data_symbols, entry)
  3500.      int use_data_symbols;
  3501.      struct file_entry *entry;
  3502. {
  3503.   struct line_debug_entry
  3504.     *state_pointer
  3505.       = (struct line_debug_entry *)
  3506.     xmalloc (3 * sizeof (struct line_debug_entry));
  3507.   register struct line_debug_entry
  3508.     *current = state_pointer,
  3509.     *next = state_pointer + 1,
  3510.     *source = state_pointer + 2; /* Used to store source file */
  3511.  
  3512.   struct nlist *tmp;
  3513.  
  3514.   for (tmp = entry->symbols;
  3515.        tmp < (entry->symbols
  3516.           + entry->syms_size/sizeof (struct nlist));
  3517.        tmp++)
  3518.     if (tmp->n_type == (int) N_SO)
  3519.       break;
  3520.  
  3521.   if (tmp >= (entry->symbols
  3522.           + entry->syms_size/sizeof (struct nlist)))
  3523.     {
  3524.       /* I believe this translates to "We lose" */
  3525.       current->filename = next->filename = entry->filename;
  3526.       current->line = next->line = -1;
  3527.       current->sym = next->sym = (struct nlist *) 0;
  3528.       return state_pointer;
  3529.     }
  3530.  
  3531.   next->line = source->line = 0;
  3532.   next->filename = source->filename
  3533.     = (tmp->n_un.n_strx + entry->strings);
  3534.   source->sym = (struct nlist *) entry;
  3535.   next->sym = tmp;
  3536.  
  3537.   next_debug_entry (use_data_symbols, state_pointer); /* To setup next */
  3538.  
  3539.   if (!next->sym)        /* No line numbers for this section; */
  3540.                 /* setup output results as appropriate */
  3541.     {
  3542.       if (source->line)
  3543.     {
  3544.       current->filename = source->filename = entry->filename;
  3545.       current->line = -1;    /* Don't print lineno */
  3546.     }
  3547.       else
  3548.     {
  3549.       current->filename = source->filename;
  3550.       current->line = 0;
  3551.     }
  3552.       return state_pointer;
  3553.     }
  3554.  
  3555.  
  3556.   next_debug_entry (use_data_symbols, state_pointer); /* To setup current */
  3557.  
  3558.   return state_pointer;
  3559. }
  3560.  
  3561. /* Takes an ADDRESS (in either text or data space) and a STATE_POINTER
  3562.    which describes the current location in the implied scan through
  3563.    the debug symbols within the file which ADDRESS is within, and
  3564.    returns the source line number which corresponds to ADDRESS.  */
  3565.  
  3566. int
  3567. address_to_line (address, state_pointer)
  3568.      unsigned long address;
  3569.      /* Next must be passed by reference! */
  3570.      struct line_debug_entry state_pointer[3];
  3571. {
  3572.   struct line_debug_entry
  3573.     *current = state_pointer,
  3574.     *next = state_pointer + 1;
  3575.   struct line_debug_entry *tmp_pointer;
  3576.  
  3577.   int use_data_symbols;
  3578.  
  3579.   if (next->sym)
  3580.     use_data_symbols = (next->sym->n_type & ~N_EXT) == N_DATA;
  3581.   else
  3582.     return current->line;
  3583.  
  3584.   /* Go back to the beginning if we've already passed it.  */
  3585.   if (current->sym->n_value > address)
  3586.     {
  3587.       tmp_pointer = init_debug_scan (use_data_symbols,
  3588.                      (struct file_entry *)
  3589.                      ((state_pointer + 2)->sym));
  3590.       state_pointer[0] = tmp_pointer[0];
  3591.       state_pointer[1] = tmp_pointer[1];
  3592.       state_pointer[2] = tmp_pointer[2];
  3593.       free (tmp_pointer);
  3594.     }
  3595.  
  3596.   /* If we're still in a bad way, return -1, meaning invalid line.  */
  3597.   if (current->sym->n_value > address)
  3598.     return -1;
  3599.  
  3600.   while (next->sym
  3601.      && next->sym->n_value <= address
  3602.      && next_debug_entry (use_data_symbols, state_pointer))
  3603.     ;
  3604.   return current->line;
  3605. }
  3606.  
  3607.  
  3608. /* Macros for manipulating bitvectors.  */
  3609. #define    BIT_SET_P(bv, index)    ((bv)[(index) >> 3] & 1 << ((index) & 0x7))
  3610. #define    SET_BIT(bv, index)    ((bv)[(index) >> 3] |= 1 << ((index) & 0x7))
  3611.  
  3612. /* This routine will scan through the relocation data of file ENTRY,
  3613.    printing out references to undefined symbols and references to
  3614.    symbols defined in files with N_WARNING symbols.  If DATA_SEGMENT
  3615.    is non-zero, it will scan the data relocation segment (and use
  3616.    N_DSLINE symbols to track line number); otherwise it will scan the
  3617.    text relocation segment.  Warnings will be printed on the output
  3618.    stream OUTFILE.  Eventually, every nlist symbol mapped through will
  3619.    be marked in the NLIST_BITVECTOR, so we don't repeat ourselves when
  3620.    we scan the nlists themselves.  */
  3621.  
  3622. do_relocation_warnings (entry, data_segment, outfile, nlist_bitvector)
  3623.      struct file_entry *entry;
  3624.      int data_segment;
  3625.      FILE *outfile;
  3626.      unsigned char *nlist_bitvector;
  3627. {
  3628.   struct relocation_info
  3629.     *reloc_start = data_segment ? entry->datarel : entry->textrel,
  3630.     *reloc;
  3631.   int reloc_size
  3632.     = ((data_segment ? entry->data_reloc_size : entry->text_reloc_size)
  3633.        / sizeof (struct relocation_info));
  3634.   int start_of_segment
  3635.     = (data_segment ? entry->data_start_address : entry->text_start_address);
  3636.   struct nlist *start_of_syms = entry->symbols;
  3637.   struct line_debug_entry *state_pointer
  3638.     = init_debug_scan (data_segment != 0, entry);
  3639.   register struct line_debug_entry *current = state_pointer;
  3640.   /* Assigned to generally static values; should not be written into.  */
  3641.   char *errfmt;
  3642.   /* Assigned to alloca'd values cand copied into; should be freed
  3643.      when done.  */
  3644.   char *errmsg;
  3645.   int invalidate_line_number;
  3646.  
  3647.   /* We need to sort the relocation info here.  Sheesh, so much effort
  3648.      for one lousy error optimization. */
  3649.  
  3650.   qsort (reloc_start, reloc_size, sizeof (struct relocation_info),
  3651.      relocation_entries_relation);
  3652.  
  3653.   for (reloc = reloc_start;
  3654.        reloc < (reloc_start + reloc_size);
  3655.        reloc++)
  3656.     {
  3657.       register struct nlist *s;
  3658.       register symbol *g;
  3659.  
  3660.       /* If the relocation isn't resolved through a symbol, continue */
  3661.       if (!RELOC_EXTERN_P(reloc))
  3662.     continue;
  3663.  
  3664.       s = &(entry->symbols[RELOC_SYMBOL(reloc)]);
  3665.  
  3666.       /* Local symbols shouldn't ever be used by relocation info, so
  3667.      the next should be safe.
  3668.      This is, of course, wrong.  References to local BSS symbols can be
  3669.      the targets of relocation info, and they can (must) be
  3670.      resolved through symbols.  However, these must be defined properly,
  3671.      (the assembler would have caught it otherwise), so we can
  3672.      ignore these cases.  */
  3673.       if (!(s->n_type & N_EXT))
  3674.     continue;
  3675.  
  3676.       g = (symbol *) s->n_un.n_name;
  3677.       errmsg = 0;
  3678.  
  3679.       if (!g->defined && list_unresolved_refs) /* Reference */
  3680.     {
  3681.       /* Mark as being noted by relocation warning pass.  */
  3682.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3683.  
  3684.       if (g->undef_refs >= MAX_UREFS_PRINTED)    /* Listed too many */
  3685.         continue;
  3686.  
  3687.       /* Undefined symbol which we should mention */
  3688.  
  3689.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3690.         {
  3691.           errfmt = "More undefined symbol %s refs follow";
  3692.           invalidate_line_number = 1;
  3693.         }
  3694.       else
  3695.         {
  3696.           errfmt = "Undefined symbol %s referenced from %s segment";
  3697.           invalidate_line_number = 0;
  3698.         }
  3699.     }
  3700.       else                         /* Defined */
  3701.     {
  3702.       /* Potential symbol warning here */
  3703.       if (!g->warning) continue;
  3704.  
  3705.       /* Mark as being noted by relocation warning pass.  */
  3706.       SET_BIT (nlist_bitvector, s - start_of_syms);
  3707.  
  3708.       errfmt = 0;
  3709.       errmsg = g->warning;
  3710.       invalidate_line_number = 0;
  3711.     }
  3712.  
  3713.  
  3714.       /* If errfmt == 0, errmsg has already been defined.  */
  3715.       if (errfmt != 0)
  3716.     {
  3717.       char *nm;
  3718.  
  3719.       if (!demangler || !(nm = (*demangler)(g->name)))
  3720.         nm = g->name;
  3721.       errmsg = xmalloc (strlen (errfmt) + strlen (nm) + 1);
  3722.       sprintf (errmsg, errfmt, nm, data_segment ? "data" : "text");
  3723.       if (nm != g->name)
  3724.         free (nm);
  3725.     }
  3726.  
  3727.       address_to_line (RELOC_ADDRESS (reloc) + start_of_segment,
  3728.                state_pointer);
  3729.  
  3730.       if (current->line >=0)
  3731.     {
  3732.       fprintf (outfile, "%s:%d (", current->filename,
  3733.            invalidate_line_number ? 0 : current->line);
  3734.       print_file_name (entry, outfile);
  3735.       fprintf (outfile, "): %s\n", errmsg);
  3736.     }
  3737.       else
  3738.     {
  3739.       print_file_name(entry, outfile);
  3740.       fprintf(outfile, ": %s\n", errmsg);
  3741.     }
  3742.  
  3743.       if (errfmt != 0)
  3744.     free (errmsg);
  3745.     }
  3746.  
  3747.   free (state_pointer);
  3748. }
  3749.  
  3750. /* Print on OUTFILE a list of all warnings generated by references
  3751.    and/or definitions in the file ENTRY.  List source file and line
  3752.    number if possible, just the .o file if not. */
  3753.  
  3754. void
  3755. do_file_warnings (entry, outfile)
  3756.      struct file_entry *entry;
  3757.      FILE *outfile;
  3758. {
  3759.   int number_of_syms = entry->syms_size / sizeof (struct nlist);
  3760.   unsigned char *nlist_bitvector
  3761.     = (unsigned char *) alloca ((number_of_syms >> 3) + 1);
  3762.   struct line_debug_entry *text_scan, *data_scan;
  3763.   int i;
  3764.   char *errfmt, *file_name;
  3765.   int line_number;
  3766.   int dont_allow_symbol_name;
  3767.  
  3768.   bzero (nlist_bitvector, (number_of_syms >> 3) + 1);
  3769.  
  3770.   /* Read in the files strings if they aren't available */
  3771.   if (!entry->strings)
  3772.     {
  3773.       int desc;
  3774.  
  3775.       entry->strings = (char *) alloca (entry->strs_size);
  3776.       desc = file_open (entry);
  3777.       read_entry_strings (desc, entry);
  3778.     }
  3779.  
  3780.   read_file_relocation (entry);
  3781.  
  3782.   /* Do text warnings based on a scan through the relocation info.  */
  3783.   do_relocation_warnings (entry, 0, outfile, nlist_bitvector);
  3784.  
  3785.   /* Do data warnings based on a scan through the relocation info.  */
  3786.   do_relocation_warnings (entry, 1, outfile, nlist_bitvector);
  3787.  
  3788.   /* Scan through all of the nlist entries in this file and pick up
  3789.      anything that the scan through the relocation stuff didn't.  */
  3790.  
  3791.   text_scan = init_debug_scan (0, entry);
  3792.   data_scan = init_debug_scan (1, entry);
  3793.  
  3794.   for (i = 0; i < number_of_syms; i++)
  3795.     {
  3796.       struct nlist *s;
  3797.       struct glosym *g;
  3798.  
  3799.       s = entry->symbols + i;
  3800.  
  3801.       if (!(s->n_type & N_EXT))
  3802.     continue;
  3803.  
  3804.       g = (symbol *) s->n_un.n_name;
  3805.       dont_allow_symbol_name = 0;
  3806.  
  3807.       if (list_multiple_defs && g->multiply_defined)
  3808.     {
  3809.       errfmt = "Definition of symbol %s (multiply defined)";
  3810.       switch (s->n_type)
  3811.         {
  3812.         case N_TEXT | N_EXT:
  3813.           line_number = address_to_line (s->n_value, text_scan);
  3814.           file_name = text_scan[0].filename;
  3815.           break;
  3816.         case N_DATA | N_EXT:
  3817.           line_number = address_to_line (s->n_value, data_scan);
  3818.           file_name = data_scan[0].filename;
  3819.           break;
  3820.         case N_SETA | N_EXT:
  3821.         case N_SETT | N_EXT:
  3822.         case N_SETD | N_EXT:
  3823.         case N_SETB | N_EXT:
  3824.           if (g->multiply_defined == 2)
  3825.         continue;
  3826.           errfmt = "First set element definition of symbol %s (multiply defined)";
  3827.           break;
  3828.         default:
  3829.           continue;        /* Don't print out multiple defs
  3830.                    at references.  */
  3831.         }
  3832.     }
  3833.       else if (BIT_SET_P (nlist_bitvector, i))
  3834.     continue;
  3835.       else if (list_unresolved_refs && !g->defined)
  3836.     {
  3837.       if (g->undef_refs >= MAX_UREFS_PRINTED)
  3838.         continue;
  3839.  
  3840.       if (++(g->undef_refs) == MAX_UREFS_PRINTED)
  3841.         errfmt = "More undefined \"%s\" refs follow";
  3842.       else
  3843.         errfmt = "Undefined symbol \"%s\" referenced";
  3844.       line_number = -1;
  3845.     }
  3846.       else if (g->warning)
  3847.     {
  3848.       /* There are two cases in which we don't want to
  3849.          do this.  The first is if this is a definition instead of
  3850.          a reference.  The second is if it's the reference used by
  3851.          the warning stabs itself.  */
  3852.       if (s->n_type != (N_EXT | N_UNDF)
  3853.           || (i && (s-1)->n_type == N_WARNING))
  3854.         continue;
  3855.  
  3856.       errfmt = g->warning;
  3857.       line_number = -1;
  3858.       dont_allow_symbol_name = 1;
  3859.     }
  3860.       else
  3861.     continue;
  3862.  
  3863.       if (line_number == -1)
  3864.     {
  3865.       print_file_name (entry, outfile);
  3866.       fprintf (outfile, ": ");
  3867.     }
  3868.       else
  3869.     {
  3870.       fprintf (outfile, "%s:%d (", file_name, line_number);
  3871.       print_file_name (entry, outfile);
  3872.       fprintf (outfile, "): ");
  3873.     }
  3874.  
  3875.       if (dont_allow_symbol_name)
  3876.     fprintf (outfile, "%s", errfmt);
  3877.       else
  3878.     {
  3879.       char *nm;
  3880.  
  3881.       if (!demangler || !(nm = (*demangler)(g->name)))
  3882.         fprintf (outfile, errfmt, g->name);
  3883.       else
  3884.         {
  3885.           fprintf (outfile, errfmt, nm);
  3886.           free (nm);
  3887.         }
  3888.     }
  3889.  
  3890.       fputc ('\n', outfile);
  3891.     }
  3892.   free (text_scan);
  3893.   free (data_scan);
  3894.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  3895. }
  3896.  
  3897. do_warnings (outfile)
  3898.      FILE *outfile;
  3899. {
  3900.   list_unresolved_refs = output_style != OUTPUT_RELOCATABLE && undefined_global_sym_count;
  3901.   list_warning_symbols = warning_count;
  3902.   list_multiple_defs = multiple_def_count != 0;
  3903.  
  3904.   if (!(list_unresolved_refs ||
  3905.     list_warning_symbols ||
  3906.     list_multiple_defs      ))
  3907.     /* No need to run this routine */
  3908.     return;
  3909.  
  3910.   each_file (do_file_warnings, outfile);
  3911.  
  3912.   if (list_unresolved_refs || list_multiple_defs)
  3913.     make_executable = 0;
  3914. }
  3915.  
  3916. #ifdef A_OUT
  3917.  
  3918. /* Stuff pertaining to creating a.out files. */
  3919.  
  3920. /* The a.out header. */
  3921.  
  3922. struct exec outheader;
  3923.  
  3924. #ifdef COFF_ENCAPSULATE
  3925. int need_coff_header;
  3926. struct coffheader coffheader;
  3927. #endif
  3928.  
  3929. /* Compute text_start and text_header_size for an a.out file.  */
  3930.  
  3931. void
  3932. initialize_a_out_text_start ()
  3933. {
  3934.   int magic;
  3935.  
  3936.   switch (output_style)
  3937.     {
  3938.     case OUTPUT_RELOCATABLE:
  3939.     case OUTPUT_WRITABLE_TEXT:
  3940.       magic = OMAGIC;
  3941.       break;
  3942.     case OUTPUT_READONLY_TEXT:
  3943. #ifdef NMAGIC
  3944.       magic = NMAGIC;
  3945.       break;
  3946. #endif
  3947.     case OUTPUT_DEMAND_PAGED:
  3948.       magic = ZMAGIC;
  3949.       break;
  3950.     default:
  3951.       fatal ("unknown output style found (bug in ld)", (char *) 0);
  3952.       break;
  3953.     }
  3954.  
  3955.   /* Determine whether to count the header as part of
  3956.      the text size, and initialize the text size accordingly.
  3957.      This depends on the kind of system and on the output format selected.  */
  3958.   N_SET_MAGIC (outheader, magic);
  3959. #ifdef INITIALIZE_HEADER
  3960.   INITIALIZE_HEADER;
  3961. #endif
  3962.  
  3963.   text_header_size = sizeof (struct exec);
  3964. #ifdef COFF_ENCAPSULATE
  3965.   /* Don't write the coff header for the output of ld -A (since
  3966.      it is not executable by the kernel anyway).  */
  3967.   if (output_style != OUTPUT_RELOCATABLE && !file_table[0].just_syms_flag)
  3968.     {
  3969.       need_coff_header = 1;
  3970.       /* set this flag now, since it will change the values of N_TXTOFF, etc */
  3971.       N_SET_FLAGS (outheader, N_FLAGS_COFF_ENCAPSULATE);
  3972.       text_header_size += sizeof (struct coffheader);
  3973.     }
  3974. #endif
  3975.   if (text_header_size <= N_TXTOFF (outheader))
  3976.     text_header_size = 0;
  3977.   else
  3978.     text_header_size -= N_TXTOFF (outheader);
  3979.  
  3980. #ifdef _N_BASEADDR
  3981.   /* SunOS 4.1 N_TXTADDR depends on the value of outheader.a_entry. */
  3982.   outheader.a_entry = N_PAGSIZ(outheader);
  3983. #endif
  3984.  
  3985.   if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  3986.     text_start = N_TXTADDR (outheader);
  3987. }
  3988.  
  3989. /* Compute data_start once text_size is known. */
  3990.  
  3991. void
  3992. initialize_a_out_data_start ()
  3993. {
  3994.   outheader.a_text = text_size;
  3995. #if TARGET_MACHINE==TARGET_SEQUENT
  3996.   outheader.a_text += N_ADDRADJ (outheader);
  3997.   if (entry_symbol == 0)
  3998.     entry_symbol = getsym ("start");
  3999. #endif
  4000.   if (! Tdata_flag_specified)
  4001.     data_start = N_DATADDR (outheader) + text_start - N_TXTADDR (outheader);
  4002. }
  4003.  
  4004. /* Compute offsets of various pieces of the a.out output file.  */
  4005.  
  4006. void
  4007. compute_a_out_section_offsets ()
  4008. {
  4009.   outheader.a_data = data_size;
  4010.   outheader.a_bss = bss_size;
  4011.   outheader.a_entry = (entry_symbol ? entry_symbol->value
  4012.                : text_start + text_header_size);
  4013.  
  4014. #ifdef COFF_ENCAPSULATE
  4015.   if (need_coff_header)
  4016.     {
  4017.       /* We are encapsulating BSD format within COFF format.  */
  4018.       struct coffscn *tp, *dp, *bp;
  4019.  
  4020.       tp = &coffheader.scns[0];
  4021.       dp = &coffheader.scns[1];
  4022.       bp = &coffheader.scns[2];
  4023.  
  4024.       strcpy (tp->s_name, ".text");
  4025.       tp->s_paddr = text_start;
  4026.       tp->s_vaddr = text_start;
  4027.       tp->s_size = text_size;
  4028.       tp->s_scnptr = sizeof (struct coffheader) + sizeof (struct exec);
  4029.       tp->s_relptr = 0;
  4030.       tp->s_lnnoptr = 0;
  4031.       tp->s_nreloc = 0;
  4032.       tp->s_nlnno = 0;
  4033.       tp->s_flags = 0x20;
  4034.       strcpy (dp->s_name, ".data");
  4035.       dp->s_paddr = data_start;
  4036.       dp->s_vaddr = data_start;
  4037.       dp->s_size = data_size;
  4038.       dp->s_scnptr = tp->s_scnptr + tp->s_size;
  4039.       dp->s_relptr = 0;
  4040.       dp->s_lnnoptr = 0;
  4041.       dp->s_nreloc = 0;
  4042.       dp->s_nlnno = 0;
  4043.       dp->s_flags = 0x40;
  4044.       strcpy (bp->s_name, ".bss");
  4045.       bp->s_paddr = dp->s_vaddr + dp->s_size;
  4046.       bp->s_vaddr = bp->s_paddr;
  4047.       bp->s_size = bss_size;
  4048.       bp->s_scnptr = 0;
  4049.       bp->s_relptr = 0;
  4050.       bp->s_lnnoptr = 0;
  4051.       bp->s_nreloc = 0;
  4052.       bp->s_nlnno = 0;
  4053.       bp->s_flags = 0x80;
  4054.  
  4055.       coffheader.f_magic = COFF_MAGIC;
  4056.       coffheader.f_nscns = 3;
  4057.       /* store an unlikely time so programs can
  4058.        * tell that there is a bsd header
  4059.        */
  4060.       coffheader.f_timdat = 1;
  4061.       coffheader.f_symptr = 0;
  4062.       coffheader.f_nsyms = 0;
  4063.       coffheader.f_opthdr = 28;
  4064.       coffheader.f_flags = 0x103;
  4065.       /* aouthdr */
  4066.       coffheader.magic = ZMAGIC;
  4067.       coffheader.vstamp = 0;
  4068.       coffheader.tsize = tp->s_size;
  4069.       coffheader.dsize = dp->s_size;
  4070.       coffheader.bsize = bp->s_size;
  4071.       coffheader.entry = outheader.a_entry;
  4072.       coffheader.text_start = tp->s_vaddr;
  4073.       coffheader.data_start = dp->s_vaddr;
  4074.     }
  4075. #endif
  4076.  
  4077.   if (strip_symbols == STRIP_ALL)
  4078.     nsyms = 0;
  4079.   else
  4080.     {
  4081.       nsyms = (defined_global_sym_count
  4082.            + undefined_global_sym_count);
  4083.       if (discard_locals == DISCARD_L)
  4084.     nsyms += non_L_local_sym_count;
  4085.       else if (discard_locals == DISCARD_NONE)
  4086.     nsyms += local_sym_count;
  4087.       /* One extra for following reference on indirects */
  4088.       if (output_style == OUTPUT_RELOCATABLE)
  4089. #ifndef NeXT
  4090.     nsyms += set_symbol_count + global_indirect_count;
  4091. #else
  4092.         nsyms += set_symbol_count;
  4093. #endif
  4094.     }
  4095.  
  4096.   if (strip_symbols == STRIP_NONE)
  4097.     nsyms += debugger_sym_count;
  4098.  
  4099.   outheader.a_syms = nsyms * sizeof (struct nlist);
  4100.  
  4101.   if (output_style == OUTPUT_RELOCATABLE)
  4102.     {
  4103.       outheader.a_trsize = text_reloc_size;
  4104.       outheader.a_drsize = data_reloc_size;
  4105.     }
  4106.   else
  4107.     {
  4108.       outheader.a_trsize = 0;
  4109.       outheader.a_drsize = 0;
  4110.     }
  4111.  
  4112.   /* Initialize the various file offsets.  */
  4113.  
  4114.   output_text_offset = N_TXTOFF (outheader);
  4115. #ifdef N_DATOFF
  4116.   output_data_offset = N_DATOFF (outheader);
  4117. #else
  4118.   output_data_offset = output_text_offset + text_size;
  4119. #endif
  4120. #ifdef N_TRELOFF
  4121.   output_trel_offset = N_TRELOFF (outheader);
  4122. #else
  4123.   output_trel_offset = output_data_offset + data_size;
  4124. #endif
  4125. #ifdef N_DRELOFF
  4126.   output_drel_offset = N_DRELOFF (outheader);
  4127. #else
  4128.   output_drel_offset = output_trel_offset + text_reloc_size;
  4129. #endif
  4130.   output_syms_offset = N_SYMOFF (outheader);
  4131.   output_strs_offset = N_STROFF (outheader);
  4132. }
  4133.  
  4134. /* Compute more section offsets once the size of the string table is known.  */
  4135.  
  4136. void
  4137. compute_more_a_out_section_offsets ()
  4138. {
  4139.   output_symseg_offset = output_strs_offset + output_strs_size;
  4140. }
  4141.  
  4142. /* Write the a.out header once everything else is known.  */
  4143.  
  4144. void
  4145. write_a_out_header ()
  4146. {
  4147.   lseek (outdesc, 0L, 0);
  4148.  
  4149. #ifdef COFF_ENCAPSULATE
  4150.   if (need_coff_header)
  4151.     mywrite (&coffheader, sizeof coffheader, 1, outdesc);
  4152. #endif
  4153.  
  4154. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4155.   fix_exec_header_byte_order(&outheader);
  4156. #endif
  4157.   mywrite (&outheader, sizeof (struct exec), 1, outdesc);
  4158. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4159.   fix_exec_header_byte_order(&outheader);
  4160. #endif
  4161.  
  4162.   /* Output whatever padding is required in the executable file
  4163.      between the header and the start of the text.  */
  4164.  
  4165. #ifndef COFF_ENCAPSULATE
  4166.   padfile (N_TXTOFF (outheader) - sizeof outheader, outdesc);
  4167. #endif
  4168. }
  4169.  
  4170. #endif
  4171.  
  4172. #ifdef MACH_O
  4173.  
  4174. /* Stuff pertaining to creating Mach-O files. */
  4175.  
  4176. /* Convert the Mach-O style n_sect references into something the rest
  4177.    of the loader can understand.  */
  4178.  
  4179. void
  4180. translate_mach_o_symbols (entry)
  4181.      struct file_entry *entry;
  4182. {
  4183.   int i, n, g;
  4184.   struct nlist *sym;
  4185.  
  4186.   n = entry->syms_size / sizeof (struct nlist);
  4187.   for (i = 0; i < n; ++i)
  4188.     if (((sym = &entry->symbols[i])->n_type & ~N_EXT) == N_SECT)
  4189.       {
  4190.     if (sym->n_sect == entry->text_ordinal)
  4191.       sym->n_type = (sym->n_type & N_EXT) | N_TEXT;
  4192.     else if (sym->n_sect == entry->data_ordinal)
  4193.       sym->n_type = (sym->n_type & N_EXT) | N_DATA;
  4194.     else if (sym->n_sect == entry->bss_ordinal)
  4195.       sym->n_type = (sym->n_type & N_EXT) | N_BSS;
  4196.     else
  4197.       fatal_with_file ("unknown section referenced in symbols of ", entry);
  4198.     sym->n_sect = 0;
  4199.       }
  4200.     else if ((sym = &entry->symbols[i])->n_type == N_SLINE)
  4201.       {
  4202.     if (sym->n_sect == entry->text_ordinal)
  4203.       sym->n_type = N_SLINE;
  4204.     else if (sym->n_sect == entry->data_ordinal)
  4205.       sym->n_type = N_DSLINE;
  4206.     else if (sym->n_sect == entry->bss_ordinal)
  4207.       sym->n_type = N_BSLINE;
  4208.     else
  4209.       fatal_with_file ("unknown section referenced in debugging symbols of ", entry);
  4210.       }
  4211. }
  4212.  
  4213. /* Convert Mach-O style relocation info into a.out style relocation
  4214.    info internally.  */
  4215. void
  4216. translate_mach_o_relocation (entry, reloc, count)
  4217.      struct file_entry *entry;
  4218.      struct relocation_info *reloc;
  4219.      int count;
  4220. {
  4221.   int i;
  4222.  
  4223.   for (i = 0; i < count; ++i)
  4224.     if (!RELOC_EXTERN_P(&reloc[i]))
  4225.       if (RELOC_TYPE(&reloc[i]) == R_ABS)
  4226.     RELOC_TYPE(&reloc[i]) = N_ABS;
  4227.       else if (RELOC_TYPE(&reloc[i]) == entry->text_ordinal)
  4228.     RELOC_TYPE(&reloc[i]) = N_TEXT;
  4229.       else if (RELOC_TYPE(&reloc[i]) == entry->data_ordinal)
  4230.     RELOC_TYPE(&reloc[i]) = N_DATA;
  4231.       else if (RELOC_TYPE(&reloc[i]) == entry->bss_ordinal)
  4232.     RELOC_TYPE(&reloc[i]) = N_BSS;
  4233.       else
  4234.     fatal_with_file ("unknown section ordinal in relocation info of ", entry);
  4235. }
  4236.  
  4237. /* Header structure for OUTPUT_RELOCATABLE.  */
  4238.  
  4239. struct
  4240. {
  4241.   struct mach_header header;
  4242.   struct segment_command segment;
  4243.   struct section text;
  4244.   struct section data;
  4245.   struct section bss;
  4246.   struct symtab_command symtab;
  4247. #ifdef LC_SYMSEG
  4248.   struct symseg_command symseg;
  4249. #endif
  4250. } m_object;
  4251.  
  4252. #ifdef NeXT
  4253. #define CPU_TYPE CPU_TYPE_MC68030
  4254. #define CPU_SUBTYPE CPU_SUBTYPE_NeXT
  4255. #define THREAD_FLAVOR NeXT_THREAD_STATE_REGS
  4256. #define THREAD_COUNT NeXT_THREAD_STATE_REGS_COUNT
  4257. typedef struct NeXT_thread_state_regs thread_state;
  4258. #define thread_state_entry_field pc
  4259. #endif
  4260.  
  4261. /* Header structure for all executable output forms.  */
  4262.  
  4263. struct
  4264. {
  4265.   struct mach_header header;
  4266.   struct segment_command pagezero;
  4267.   struct segment_command text_segment;
  4268.   struct section text;
  4269.   struct segment_command data_segment;
  4270.   struct section data;
  4271.   struct section bss;
  4272.   struct thread_command unixthread;
  4273.   unsigned long int flavor;
  4274.   unsigned long int count;
  4275.   thread_state state;
  4276.   struct symtab_command symtab;
  4277. #ifdef LC_SYMSEG
  4278.   struct symseg_command symseg;
  4279. #endif
  4280. } m_exec;
  4281.  
  4282. /* Compute text_start and text_header_size for an a.out file.  */
  4283.  
  4284. void
  4285. initialize_mach_o_text_start ()
  4286. {
  4287.   if (output_style != OUTPUT_RELOCATABLE)
  4288.     {
  4289.       text_header_size = sizeof m_exec;
  4290.       if (!T_flag_specified && output_style != OUTPUT_RELOCATABLE)
  4291.     /* We reserve the first page of an executable to trap NULL dereferences.  */
  4292.     text_start = page_size;
  4293.     }
  4294. }
  4295.  
  4296. /* Compute data_start once text_size is known.  */
  4297.  
  4298. void
  4299. initialize_mach_o_data_start ()
  4300. {
  4301.   if (! Tdata_flag_specified)
  4302.     data_start = text_start + text_size;
  4303. }
  4304.  
  4305. /* Compute offsets of various pieces of the Mach-O output file.  */
  4306. void
  4307. compute_mach_o_section_offsets ()
  4308. {
  4309.   int header_size, trsize, drsize;
  4310.  
  4311.   switch (output_style)
  4312.     {
  4313.     case OUTPUT_RELOCATABLE:
  4314.       header_size = sizeof m_object;
  4315.       break;
  4316.     default:
  4317.       header_size = sizeof m_exec;
  4318.       break;
  4319.     }
  4320.  
  4321.   if (strip_symbols == STRIP_ALL)
  4322.     nsyms = 0;
  4323.   else
  4324.     {
  4325.       nsyms = (defined_global_sym_count
  4326.            + undefined_global_sym_count);
  4327.       if (discard_locals == DISCARD_L)
  4328.     nsyms += non_L_local_sym_count;
  4329.       else if (discard_locals == DISCARD_NONE)
  4330.     nsyms += local_sym_count;
  4331.       /* One extra for following reference on indirects */
  4332.       if (output_style == OUTPUT_RELOCATABLE)
  4333. #if TARGET_MACHINEN==TARGET_NeXT
  4334.         nsyms += set_symbol_count;
  4335. #else
  4336.     nsyms += set_symbol_count + global_indirect_count;
  4337. #endif
  4338.     }
  4339.  
  4340.   if (strip_symbols == STRIP_NONE)
  4341.     nsyms += debugger_sym_count;
  4342.  
  4343.   if (output_style != OUTPUT_RELOCATABLE)
  4344.     output_text_offset = header_size;
  4345.   output_data_offset = output_text_offset + text_size;
  4346.   output_trel_offset = output_data_offset + data_size;
  4347.   if (output_style == OUTPUT_RELOCATABLE)
  4348.     trsize = text_reloc_size, drsize = data_reloc_size;
  4349.   else
  4350.     trsize = drsize = 0;
  4351.   output_drel_offset = output_trel_offset + trsize;
  4352.   output_syms_offset = output_drel_offset + drsize;
  4353.   output_strs_offset = output_syms_offset + nsyms * sizeof (struct nlist);
  4354. }
  4355.  
  4356. /* Compute more section offsets once the size of the string table is known.  */
  4357. void
  4358. compute_more_mach_o_section_offsets ()
  4359. {
  4360.   output_symseg_offset = output_strs_offset + output_strs_size;
  4361. }
  4362.  
  4363. /* Write the Mach-O header once everything else is known.  */
  4364.  
  4365. void
  4366. write_mach_o_header ()
  4367. {
  4368.   struct mach_header header;
  4369.   struct section text, data, bss;
  4370.   struct symtab_command symtab;
  4371. #ifdef LC_SYMSEG
  4372.   struct symseg_command symseg;
  4373. #endif
  4374.   thread_state state;
  4375.  
  4376.   lseek (outdesc, 0L, 0);
  4377.  
  4378.  
  4379.   header.magic = MH_MAGIC;
  4380.   header.cputype = CPU_TYPE;
  4381.   header.cpusubtype = CPU_SUBTYPE;
  4382.   header.filetype = output_style == OUTPUT_RELOCATABLE ? MH_OBJECT : MH_EXECUTE;
  4383. #ifdef LC_SYMSEG
  4384.   switch (output_style)
  4385.     {
  4386.     case OUTPUT_RELOCATABLE:
  4387.       header.ncmds = 3;
  4388.       header.sizeofcmds = sizeof m_object - sizeof header;
  4389.       break;
  4390.     default:
  4391.       header.ncmds = 6;
  4392.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4393.       break;
  4394.     }
  4395. #else
  4396.   switch (output_style)
  4397.     {
  4398.     case OUTPUT_RELOCATABLE:
  4399.       header.ncmds = 2;
  4400.       header.sizeofcmds = sizeof m_object - sizeof header;
  4401.       break;
  4402.     default:
  4403.       header.ncmds = 5;
  4404.       header.sizeofcmds = sizeof m_exec - sizeof header;
  4405.       break;
  4406.     }
  4407. #endif
  4408.   header.flags = undefined_global_sym_count ? 0 : MH_NOUNDEFS;
  4409.  
  4410.   bzero((char *) &text, sizeof text);
  4411.   strncpy(text.sectname, SECT_TEXT, sizeof text.sectname);
  4412.   strncpy(text.segname, SEG_TEXT, sizeof text.segname);
  4413.   text.addr = text_start;
  4414.   text.size = text_size;
  4415.   text.offset = output_text_offset;
  4416.   text.align = text.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4417.   text.reloff = output_trel_offset;
  4418.   text.nreloc = output_style == OUTPUT_RELOCATABLE
  4419.     ? text_reloc_size / sizeof (struct relocation_info) : 0;
  4420.   text.flags = 0;
  4421.  
  4422.   bzero((char *) &data, sizeof data);
  4423.   strncpy(data.sectname, SECT_DATA, sizeof data.sectname);
  4424.   strncpy(data.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4425.       sizeof data.segname);
  4426.   data.addr = data_start;
  4427.   data.size = data_size;
  4428.   data.offset = output_data_offset;
  4429.   data.align = data.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4430.   data.reloff = output_drel_offset;
  4431.   data.nreloc = output_style == OUTPUT_RELOCATABLE
  4432.     ? data_reloc_size / sizeof (struct relocation_info) : 0;
  4433.   data.flags = 0;
  4434.  
  4435.   bzero((char *) &bss, sizeof bss);
  4436.   strncpy(bss.sectname, SECT_BSS, sizeof data.sectname);
  4437.   strncpy(bss.segname, output_style == OUTPUT_WRITABLE_TEXT ? SEG_TEXT : SEG_DATA,
  4438.       sizeof bss.segname);
  4439.   bss.addr = data_start + data_size;
  4440.   bss.size = bss_size;
  4441.   bss.align = bss.addr % sizeof (double) ? sizeof (int) : sizeof (double);
  4442.   bss.reloff = 0;
  4443.   bss.nreloc = 0;
  4444.   bss.flags = S_ZEROFILL;
  4445.  
  4446.   symtab.cmd = LC_SYMTAB;
  4447.   symtab.cmdsize = sizeof symtab;
  4448.   symtab.symoff = output_syms_offset;
  4449.   symtab.nsyms = output_syms_size / sizeof (struct nlist);
  4450.   symtab.stroff = output_strs_offset;
  4451.   symtab.strsize = output_strs_size;
  4452.  
  4453. #ifdef LC_SYMSEG
  4454.   symseg.cmd = LC_SYMSEG;
  4455.   symseg.cmdsize = sizeof symseg;
  4456.   symseg.offset = output_symseg_offset;
  4457.   symseg.size = output_symseg_size;
  4458. #endif
  4459.  
  4460.   switch (output_style)
  4461.     {
  4462.     case OUTPUT_RELOCATABLE:
  4463.       m_object.header = header;
  4464.       m_object.segment.cmd = LC_SEGMENT;
  4465.       m_object.segment.cmdsize = sizeof (struct segment_command) + 3 * sizeof (struct section);
  4466.       strncpy(m_object.segment.segname, SEG_TEXT, sizeof m_object.segment.segname);
  4467.       m_object.segment.vmaddr = 0;
  4468.       m_object.segment.vmsize = text.size + data.size + bss.size;
  4469.       m_object.segment.fileoff = text.offset;
  4470.       m_object.segment.filesize = text.size + data.size;
  4471.       m_object.segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4472.       m_object.segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4473.       m_object.segment.nsects = 3;
  4474.       m_object.segment.flags = 0;
  4475.       m_object.text = text;
  4476.       m_object.data = data;
  4477.       m_object.bss = bss;
  4478.       m_object.symtab = symtab;
  4479. #ifdef LC_SYMSEG
  4480.       m_object.symseg = symseg;
  4481. #endif
  4482.       mywrite((char *) &m_object, 1, sizeof m_object, outdesc);
  4483.       break;
  4484.  
  4485.     case 'Z':
  4486.       data_gap = parse (arg, "%x", "invalid argument to -Z");
  4487.       if (data_gap % page_size)
  4488.       fatal("-Z argument not a multiple of page size", 0);
  4489.       Z_flag_specified = 1;
  4490.       return;
  4491.  
  4492.     default:
  4493.       m_exec.header = header;
  4494.       m_exec.pagezero.cmd = LC_SEGMENT;
  4495.       m_exec.pagezero.cmdsize = sizeof (struct segment_command);
  4496.       strncpy(m_exec.pagezero.segname, SEG_PAGEZERO, sizeof m_exec.pagezero.segname);
  4497.       m_exec.pagezero.vmaddr = 0;
  4498.       m_exec.pagezero.vmsize = page_size;
  4499.       m_exec.pagezero.fileoff = 0;
  4500.       m_exec.pagezero.filesize = 0;
  4501.       m_exec.pagezero.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4502.       m_exec.pagezero.initprot = 0;
  4503.       m_exec.pagezero.nsects = 0;
  4504.       m_exec.pagezero.flags = 0;
  4505.       m_exec.text_segment.cmd = LC_SEGMENT;
  4506.       m_exec.text_segment.cmdsize = sizeof (struct segment_command) + sizeof (struct section);
  4507.       strncpy(m_exec.text_segment.segname, SEG_TEXT, sizeof m_exec.text_segment.segname);
  4508.       m_exec.text_segment.vmaddr = text_start;
  4509.       m_exec.text_segment.vmsize = text_size;
  4510.       m_exec.text_segment.fileoff = output_text_offset;
  4511.       m_exec.text_segment.filesize = text_size;
  4512.       m_exec.text_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4513.       m_exec.text_segment.initprot = VM_PROT_READ | VM_PROT_EXECUTE;
  4514.       if (output_style == OUTPUT_WRITABLE_TEXT)
  4515.     m_exec.text_segment.initprot |= VM_PROT_WRITE;
  4516.       m_exec.text_segment.nsects = 1;
  4517.       m_exec.text_segment.flags = 0;
  4518.       m_exec.text = text;
  4519.       m_exec.data_segment.cmd = LC_SEGMENT;
  4520.       m_exec.data_segment.cmdsize = sizeof (struct segment_command) + 2 * sizeof (struct section);
  4521.       strncpy(m_exec.data_segment.segname, SEG_DATA, sizeof m_exec.data_segment.segname);
  4522.       m_exec.data_segment.vmaddr = data_start;
  4523.       m_exec.data_segment.vmsize = data_size + bss_size;
  4524.       m_exec.data_segment.fileoff = output_data_offset;
  4525.       m_exec.data_segment.filesize = data_size;
  4526.       m_exec.data_segment.maxprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4527.       m_exec.data_segment.initprot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
  4528.       m_exec.data_segment.nsects = 2;
  4529.       m_exec.data_segment.flags = 0;
  4530.       m_exec.data = data;
  4531.       m_exec.bss = bss;
  4532.       m_exec.unixthread.cmd = LC_UNIXTHREAD;
  4533.       m_exec.unixthread.cmdsize
  4534.     = sizeof (struct thread_command) + 2 * sizeof (long int) + sizeof (thread_state);
  4535.       m_exec.flavor = THREAD_FLAVOR;
  4536.       m_exec.count = THREAD_COUNT;
  4537.       m_exec.state.thread_state_entry_field = entry_symbol
  4538.     ? entry_symbol->value : text_start + text_header_size;
  4539.       m_exec.symtab = symtab;
  4540. #ifdef LC_SYMSEG
  4541.       m_exec.symseg = symseg;
  4542. #endif
  4543.       mywrite((char *) &m_exec, 1, sizeof m_exec, outdesc);
  4544.       break;
  4545.     }
  4546. }
  4547.  
  4548.  
  4549. /* Translate a.out style symbols into Mach-O style symbols.  */
  4550.  
  4551. void
  4552. generate_mach_o_symbols (syms, nsyms)
  4553.      struct nlist *syms;
  4554.      int nsyms;
  4555. {
  4556.   int i;
  4557.  
  4558.   for (i = 0; i < nsyms; ++i)
  4559.     switch (syms[i].n_type)
  4560.       {
  4561.       case N_TEXT:
  4562.       case N_TEXT | N_EXT:
  4563.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4564.     syms[i].n_sect = 1;    /* text section ordinal */
  4565.     break;
  4566.       case N_DATA:
  4567.       case N_DATA | N_EXT:
  4568.     syms[i].n_type = syms[i].n_type & N_EXT | N_SECT;
  4569.     syms[i].n_sect = 2;    /* data section ordinal */
  4570.     break;
  4571.       case N_BSS:
  4572.       case N_BSS | N_EXT:
  4573.     syms[i].n_type = syms[i].n_type & N_EXT | N_BSS;
  4574.     syms[i].n_sect = 3;    /* bss section ordinal */
  4575.     break;
  4576.       case N_SLINE:
  4577.     syms[i].n_type = N_SLINE;
  4578.     syms[i].n_sect = 1;    /* text section ordinal */
  4579.     break;
  4580.       case N_DSLINE:
  4581.     syms[i].n_type = N_SLINE;
  4582.     syms[i].n_sect = 2;    /* data section ordinal */
  4583.     break;
  4584.       case N_BSLINE:
  4585.     syms[i].n_type = N_SLINE;
  4586.     syms[i].n_sect = 3;    /* bss section ordinal */
  4587.     break;
  4588.       }
  4589. }
  4590.  
  4591. /* Translate a.out style relocation info into Mach-O style relocation
  4592.    info.  */
  4593.  
  4594. void
  4595. generate_mach_o_relocations (reloc, nreloc)
  4596.      struct relocation_info *reloc;
  4597.      int nreloc;
  4598. {
  4599.   int i;
  4600.  
  4601.   for (i = 0; i < nreloc; ++i)
  4602.     if (!RELOC_EXTERN_P (&reloc[i]))
  4603.       switch (RELOC_TYPE (&reloc[i]))
  4604.     {
  4605.     case N_ABS:
  4606.     case N_ABS | N_EXT:
  4607.       RELOC_TYPE (&reloc[i]) = R_ABS;
  4608.       break;
  4609.     case N_TEXT:
  4610.     case N_TEXT | N_EXT:
  4611.       RELOC_TYPE (&reloc[i]) = 1; /* output text section ordinal */
  4612.       break;
  4613.     case N_DATA:
  4614.     case N_DATA | N_EXT:
  4615.       RELOC_TYPE (&reloc[i]) = 2; /* output data section ordinal */
  4616.       break;
  4617.     case N_BSS:
  4618.     case N_BSS | N_EXT:
  4619.       RELOC_TYPE (&reloc[i]) = 3; /* output bss section ordinal */
  4620.       break;
  4621.     }
  4622. }
  4623.  
  4624. #endif
  4625.  
  4626. /* The following functions are simple switches according to the
  4627.    output style.  */
  4628.  
  4629. /* Compute text_start and text_header_size as appropriate for the
  4630.    output format.  */
  4631.  
  4632. void
  4633. initialize_text_start ()
  4634. {
  4635. #ifdef A_OUT
  4636.   if (output_file_type == IS_A_OUT)
  4637.     {
  4638.       initialize_a_out_text_start ();
  4639.       return;
  4640.     }
  4641. #endif
  4642. #ifdef MACH_O
  4643.   if (output_file_type == IS_MACH_O)
  4644.     {
  4645.       initialize_mach_o_text_start ();
  4646.       return;
  4647.     }
  4648. #endif
  4649.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4650. }
  4651.  
  4652. /* Initialize data_start as appropriate to the output format, once text_size
  4653.    is known.  */
  4654.  
  4655. void
  4656. initialize_data_start ()
  4657. {
  4658. #ifdef A_OUT
  4659.   if (output_file_type == IS_A_OUT)
  4660.     {
  4661.       initialize_a_out_data_start ();
  4662.       return;
  4663.     }
  4664. #endif
  4665. #ifdef MACH_O
  4666.   if (output_file_type == IS_MACH_O)
  4667.     {
  4668.       initialize_mach_o_data_start ();
  4669.       return;
  4670.     }
  4671. #endif
  4672.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4673. }
  4674.  
  4675. /* Compute offsets of the various sections within the output file.  */
  4676.  
  4677. void
  4678. compute_section_offsets ()
  4679. {
  4680. #ifdef A_OUT
  4681.   if (output_file_type == IS_A_OUT)
  4682.     {
  4683.       compute_a_out_section_offsets ();
  4684.       return;
  4685.     }
  4686. #endif
  4687. #ifdef MACH_O
  4688.   if (output_file_type == IS_MACH_O)
  4689.     {
  4690.       compute_mach_o_section_offsets ();
  4691.       return;
  4692.     }
  4693. #endif
  4694.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4695. }
  4696.  
  4697. /* Compute more section offsets, once the size of the string table
  4698.    is finalized.  */
  4699. void
  4700. compute_more_section_offsets ()
  4701. {
  4702. #ifdef A_OUT
  4703.   if (output_file_type == IS_A_OUT)
  4704.     {
  4705.       compute_more_a_out_section_offsets ();
  4706.       return;
  4707.     }
  4708. #endif
  4709. #ifdef MACH_O
  4710.   if (output_file_type == IS_MACH_O)
  4711.     {
  4712.       compute_more_mach_o_section_offsets ();
  4713.       return;
  4714.     }
  4715. #endif
  4716.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4717. }
  4718.  
  4719. /* Write the output file header, once everything is known.  */
  4720. void
  4721. write_header ()
  4722. {
  4723. #ifdef A_OUT
  4724.   if (output_file_type == IS_A_OUT)
  4725.     {
  4726.       write_a_out_header ();
  4727.       return;
  4728.     }
  4729. #endif
  4730. #ifdef MACH_O
  4731.   if (output_file_type == IS_MACH_O)
  4732.     {
  4733.       write_mach_o_header ();
  4734.       return;
  4735.     }
  4736. #endif
  4737.   fatal ("unknown output file type (enum file_type)", (char *) 0);
  4738. }
  4739.  
  4740. /* Write the output file */
  4741.  
  4742. void
  4743. write_output ()
  4744. {
  4745.   struct stat statbuf;
  4746.   int filemode, mask;
  4747.  
  4748.   /* Remove the old file in case it is owned by someone else.
  4749.      This prevents spurious "not owner" error messages.
  4750.      Don't check for errors from unlink; we don't really care
  4751.      whether it worked.
  4752.  
  4753.      Note that this means that if the output file is hard linked,
  4754.      the other names will still have the old contents.  This is
  4755.      the way Unix ld works; I'm going to consider it a feature.  */
  4756.   (void) unlink (output_filename);
  4757.   
  4758.   outdesc = open (output_filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  4759.   if (outdesc < 0) perror_name (output_filename);
  4760.  
  4761.   if (fstat (outdesc, &statbuf) < 0)
  4762.     perror_name (output_filename);
  4763.  
  4764.   filemode = statbuf.st_mode;
  4765.  
  4766.   chmod (output_filename, filemode & ~0111);
  4767.  
  4768.   /* Calculate the offsets of the various pieces of the output file.  */
  4769.   compute_section_offsets ();
  4770.  
  4771.   /* Output the text and data segments, relocating as we go.  */
  4772.   write_text ();
  4773.   write_data ();
  4774.  
  4775.   /* Output the merged relocation info, if requested with `-r'.  */
  4776.   if (output_style == OUTPUT_RELOCATABLE)
  4777.     write_rel ();
  4778.  
  4779.   /* Output the symbol table (both globals and locals).  */
  4780.   write_syms ();
  4781.  
  4782.   /* At this point the total size of the symbol table and string table
  4783.      are finalized.  */
  4784.   compute_more_section_offsets ();
  4785.  
  4786.   /* Copy any GDB symbol segments from input files.  */
  4787.   write_symsegs ();
  4788.  
  4789.   /* Now that everything is known about the output file, write its header.  */
  4790.   write_header ();
  4791.  
  4792.   close (outdesc);
  4793.  
  4794.   mask = umask (0);
  4795.   umask (mask);
  4796.  
  4797.   if (chmod (output_filename, filemode | (0111 & ~mask)) == -1)
  4798.     perror_name (output_filename);
  4799. }
  4800.  
  4801. void modify_location (), perform_relocation (), copy_text (), copy_data ();
  4802.  
  4803. /* Relocate the text segment of each input file
  4804.    and write to the output file.  */
  4805.  
  4806. void
  4807. write_text ()
  4808. {
  4809.   if (trace_files)
  4810.     fprintf (stderr, "Copying and relocating text:\n\n");
  4811.  
  4812.   lseek (outdesc, output_text_offset + text_header_size, 0);
  4813.  
  4814.   each_full_file (copy_text, 0);
  4815.   file_close ();
  4816.  
  4817.   if (trace_files)
  4818.     fprintf (stderr, "\n");
  4819.  
  4820.   padfile (text_pad, outdesc);
  4821. }
  4822.  
  4823. /* Read in all of the relocation information */
  4824.  
  4825. void
  4826. read_relocation ()
  4827. {
  4828.   each_full_file (read_file_relocation, 0);
  4829. }
  4830.  
  4831. /* Read in the relocation sections of ENTRY if necessary */
  4832.  
  4833. void
  4834. read_file_relocation (entry)
  4835.      struct file_entry *entry;
  4836. {
  4837.   register struct relocation_info *reloc;
  4838.   int desc;
  4839.   int read_return;
  4840.  
  4841.   desc = -1;
  4842.   if (!entry->textrel)
  4843.     {
  4844.       reloc = (struct relocation_info *) xmalloc (entry->text_reloc_size);
  4845.       desc = file_open (entry);
  4846.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4847.       if (entry->text_reloc_size != (read_return = read (desc, reloc, entry->text_reloc_size)))
  4848.     {
  4849.       fprintf (stderr, "Return from read: %d\n", read_return);
  4850.       fatal_with_file ("premature eof in text relocation of ", entry);
  4851.     }
  4852. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4853.       target_to_host_reloc_byte_order(reloc,
  4854.     entry->text_reloc_size/sizeof(*reloc));
  4855. #endif
  4856.       entry->textrel = reloc;
  4857.     }
  4858.  
  4859.   if (!entry->datarel)
  4860.     {
  4861.       reloc = (struct relocation_info *) xmalloc (entry->data_reloc_size);
  4862.       if (desc == -1) desc = file_open (entry);
  4863.       lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  4864.       if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  4865.     fatal_with_file ("premature eof in data relocation of ", entry);
  4866. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4867.       target_to_host_reloc_byte_order(reloc,
  4868.     entry->data_reloc_size/sizeof(*reloc));
  4869. #endif
  4870.       entry->datarel = reloc;
  4871.     }
  4872.  
  4873. #ifdef MACH_O
  4874.   if (entry->file_type == IS_MACH_O)
  4875.     {
  4876.       translate_mach_o_relocation (entry, entry->textrel,
  4877.                    entry->text_reloc_size / sizeof (struct relocation_info));
  4878.       translate_mach_o_relocation (entry, entry->datarel,
  4879.                    entry->data_reloc_size / sizeof (struct relocation_info));
  4880.     }
  4881. #endif
  4882.  
  4883.  
  4884.   if (T_flag_specified)
  4885.       padfile (text_start - sizeof(struct exec), outdesc);
  4886.  
  4887. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4888.       target_to_host_reloc_byte_order(reloc,
  4889.     entry->text_reloc_size/sizeof(*reloc));
  4890. #endif
  4891. }
  4892.  
  4893. /* Read the text segment contents of ENTRY, relocate them,
  4894.    and write the result to the output file.
  4895.    If `-r', save the text relocation for later reuse.  */
  4896.  
  4897. void
  4898. copy_text (entry)
  4899.      struct file_entry *entry;
  4900. {
  4901.   register char *bytes;
  4902.   register int desc;
  4903.   register struct relocation_info *reloc;
  4904.  
  4905.   if (trace_files)
  4906.     prline_file_name (entry, stderr);
  4907.  
  4908.   desc = file_open (entry);
  4909.  
  4910.   /* Allocate space for the file's text section */
  4911.  
  4912.   bytes = (char *) alloca (entry->text_size);
  4913.  
  4914.   /* Deal with relocation information however is appropriate */
  4915.  
  4916.   if (entry->textrel)  reloc = entry->textrel;
  4917.   else if (output_style == OUTPUT_RELOCATABLE)
  4918.     {
  4919.       read_file_relocation (entry);
  4920.       reloc = entry->textrel;
  4921.     }
  4922.   else
  4923.     {
  4924.       reloc = (struct relocation_info *) alloca (entry->text_reloc_size);
  4925.       lseek (desc, entry->starting_offset + entry->text_reloc_offset, L_SET);
  4926.       if (entry->text_reloc_size != read (desc, reloc, entry->text_reloc_size))
  4927.     fatal_with_file ("premature eof in text relocation of ", entry);
  4928. #ifdef MACH_O
  4929.       if (entry->file_type == IS_MACH_O)
  4930.     translate_mach_o_relocation (entry, reloc,
  4931.                      entry->text_reloc_size / sizeof (struct relocation_info));
  4932. #else
  4933. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4934.       target_to_host_reloc_byte_order(reloc,
  4935.       entry->text_reloc_size/sizeof(*reloc));
  4936. #endif
  4937. #endif    
  4938.     }
  4939.  
  4940.   /* Read the text section into core.  */
  4941.  
  4942.   lseek (desc, entry->starting_offset + entry->text_offset, L_SET);
  4943.   if (entry->text_size != read (desc, bytes, entry->text_size))
  4944.     fatal_with_file ("premature eof in text section of ", entry);
  4945.  
  4946.   /* Relocate the text according to the text relocation.  */
  4947.  
  4948.   perform_relocation (bytes, entry->text_start_address - entry->orig_text_address,
  4949.               entry->text_size, reloc, entry->text_reloc_size, entry);
  4950.  
  4951.   /* Write the relocated text to the output file.  */
  4952.  
  4953.   mywrite (bytes, 1, entry->text_size, outdesc);
  4954. }
  4955.  
  4956. /* Relocate the data segment of each input file
  4957.    and write to the output file.  */
  4958.  
  4959. void
  4960. write_data ()
  4961. {
  4962.   if (trace_files)
  4963.     fprintf (stderr, "Copying and relocating data:\n\n");
  4964.  
  4965.   lseek (outdesc, output_data_offset, 0);
  4966.  
  4967.   each_full_file (copy_data, 0);
  4968.   file_close ();
  4969.  
  4970.   /* Write out the set element vectors.  See digest symbols for
  4971.      description of length of the set vector section.  */
  4972.  
  4973. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  4974.   {
  4975.     int i;
  4976.     for (i = 0; i < 2 * set_symbol_count + set_vector_count; ++i) {
  4977.     fix_byte_order(&set_vectors[i], sizeof(*set_vectors));
  4978.     }
  4979.   }
  4980. #endif
  4981.  
  4982.   if (set_vector_count)
  4983.     mywrite (set_vectors, 2 * set_symbol_count + set_vector_count,
  4984.          sizeof (unsigned long), outdesc);
  4985.  
  4986.   if (trace_files)
  4987.     fprintf (stderr, "\n");
  4988.  
  4989.   padfile (data_pad, outdesc);
  4990. }
  4991.  
  4992. /* Read the data segment contents of ENTRY, relocate them,
  4993.    and write the result to the output file.
  4994.    If `-r', save the data relocation for later reuse.
  4995.    See comments in `copy_text'.  */
  4996.  
  4997. void
  4998. copy_data (entry)
  4999.      struct file_entry *entry;
  5000. {
  5001.   register struct relocation_info *reloc;
  5002.   register char *bytes;
  5003.   register int desc;
  5004.  
  5005.   if (trace_files)
  5006.     prline_file_name (entry, stderr);
  5007.  
  5008.   desc = file_open (entry);
  5009.  
  5010.   bytes = (char *) alloca (entry->data_size);
  5011.  
  5012.   if (entry->datarel) reloc = entry->datarel;
  5013.   else if (output_style == OUTPUT_RELOCATABLE)    /* Will need this again */
  5014.     {
  5015.       read_file_relocation (entry);
  5016.       reloc = entry->datarel;
  5017.     }
  5018.   else
  5019.     {
  5020.       reloc = (struct relocation_info *) alloca (entry->data_reloc_size);
  5021.       lseek (desc, entry->starting_offset + entry->data_reloc_offset, L_SET);
  5022.       if (entry->data_reloc_size != read (desc, reloc, entry->data_reloc_size))
  5023.     fatal_with_file ("premature eof in data relocation of ", entry);
  5024. #ifdef MACH_O
  5025.       if (entry->file_type == IS_MACH_O)
  5026.     translate_mach_o_relocation (entry, reloc,
  5027.                      entry->data_reloc_size / sizeof (struct relocation_info));
  5028. #else
  5029. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5030.       target_to_host_reloc_byte_order(reloc,
  5031.       entry->data_reloc_size/sizeof(*reloc));
  5032. #endif
  5033. #endif
  5034.     }
  5035.  
  5036.   lseek (desc, entry->starting_offset + entry->data_offset, L_SET);
  5037.   if (entry->data_size != read (desc, bytes, entry->data_size))
  5038.     fatal_with_file ("premature eof in data section of ", entry);
  5039.  
  5040.   perform_relocation (bytes, entry->data_start_address - entry->orig_data_address,
  5041.               entry->data_size, reloc, entry->data_reloc_size, entry);
  5042.  
  5043.   mywrite (bytes, 1, entry->data_size, outdesc);
  5044. }
  5045.  
  5046. /* Relocate ENTRY's text or data section contents.
  5047.    DATA is the address of the contents, in core.
  5048.    DATA_SIZE is the length of the contents.
  5049.    PC_RELOCATION is the difference between the address of the contents
  5050.      in the output file and its address in the input file.
  5051.    RELOC_INFO is the address of the relocation info, in core.
  5052.    RELOC_SIZE is its length in bytes.  */
  5053. /* This version is about to be severly hacked by Randy.  Hope it
  5054.    works afterwards. */
  5055.  
  5056.  
  5057. void foobar(i)
  5058.     int i;
  5059. {
  5060.     printf("foobar(%d)\n", i);
  5061.     return;
  5062. }
  5063.  
  5064. void
  5065. perform_relocation (data, pc_relocation, data_size, reloc_info, reloc_size, entry)
  5066.      char *data;
  5067.      struct relocation_info *reloc_info;
  5068.      struct file_entry *entry;
  5069.      int pc_relocation;
  5070.      int data_size;
  5071.      int reloc_size;
  5072. {
  5073.   register struct relocation_info *p = reloc_info;
  5074.   struct relocation_info *end
  5075.     = reloc_info + reloc_size / sizeof (struct relocation_info);
  5076.   int text_relocation = entry->text_start_address - entry->orig_text_address;
  5077.   int data_relocation = entry->data_start_address - entry->orig_data_address;
  5078.   int bss_relocation = entry->bss_start_address - entry->orig_bss_address;
  5079.   struct relocation_info previous;
  5080.  
  5081.   for (; p < end; p++)
  5082.     {
  5083.       register int relocation = 0;
  5084.       register int addr = RELOC_ADDRESS(p);
  5085.       register unsigned int mask = 0;
  5086.       register unsigned int x;
  5087.  
  5088.       if (addr >= data_size)
  5089.     fatal_with_file ("relocation address out of range in ", entry);
  5090.  
  5091.       if (RELOC_EXTERN_P(p))
  5092.     {
  5093.       int symindex = RELOC_SYMBOL (p) * sizeof (struct nlist);
  5094.       symbol *sp = ((symbol *)
  5095.             (((struct nlist *)
  5096.               (((char *)entry->symbols) + symindex))
  5097.              ->n_un.n_name));
  5098.  
  5099. #ifdef N_INDR
  5100.       /* Resolve indirection */
  5101.       if ((sp->defined & ~N_EXT) == N_INDR)
  5102.         sp = (symbol *) sp->value;
  5103. #endif
  5104.  
  5105.       if (symindex >= entry->syms_size)
  5106.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5107.  
  5108.       /* If the symbol is undefined, leave it at zero.  */
  5109.       if (! sp->defined)
  5110.         relocation = 0;
  5111.       else
  5112.         relocation = sp->value;
  5113.     }
  5114. #if 1
  5115.        else if (RELOC_PCREL_P(p)) {
  5116.         /*
  5117.          * Since the symbol is not external, it must be internal.
  5118.          * Since the offset is pc-relative it has already been
  5119.          * resolved for all internal symbols.  So we just skip
  5120.          * this entry.
  5121.          */
  5122.         continue;
  5123.          }
  5124. #endif     
  5125.       else switch (RELOC_TYPE(p))
  5126.     {
  5127.     case N_TEXT:
  5128.     case N_TEXT | N_EXT:
  5129.       relocation = text_relocation;
  5130.       break;
  5131.  
  5132.     case N_DATA:
  5133.     case N_DATA | N_EXT:
  5134.       relocation = data_relocation;
  5135.       break;
  5136.  
  5137.     case N_BSS:
  5138.     case N_BSS | N_EXT:
  5139.       relocation = bss_relocation;
  5140.       break;
  5141.  
  5142.     case N_ABS:
  5143.     case N_ABS | N_EXT:
  5144.       /* Don't know why this code would occur, but apparently it does.  */
  5145.       break;
  5146.  
  5147.     default:
  5148.       fatal_with_file ("nonexternal relocation code invalid in ", entry);
  5149.     }
  5150.  
  5151.       if (RELOC_PCREL_P(p))
  5152.     relocation -= pc_relocation;
  5153.  
  5154. #ifdef RELOC_ADD_EXTRA
  5155.       relocation += RELOC_ADD_EXTRA(p);
  5156.  
  5157. #if 1
  5158.       /*
  5159.        * If the relocation fields are going to used again
  5160.        * then we need to change them up to reflect the
  5161.        * relocations performed here.
  5162.        */
  5163.  
  5164.        RELOC_ADD_EXTRA(p) = relocation;
  5165.  
  5166. #else
  5167.       if (output_style == OUTPUT_RELOCATABLE)
  5168.     {
  5169.       /* If this RELOC_ADD_EXTRA is 0, it means that the
  5170.          symbol was external and the relocation does not
  5171.          need a fixup here.  */
  5172.       if (RELOC_ADD_EXTRA (p))
  5173.         {
  5174.           if (! RELOC_PCREL_P (p))
  5175.         RELOC_ADD_EXTRA (p) = relocation;
  5176.           else
  5177.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  5178.         }
  5179. #if 0
  5180.       if (! RELOC_PCREL_P (p))
  5181.         {
  5182.           if ((int)p->r_type <= RELOC_32
  5183.           || RELOC_EXTERN_P (p) == 0)
  5184.         RELOC_ADD_EXTRA (p) = relocation;
  5185.         }
  5186.       else if (RELOC_EXTERN_P (p))
  5187.         RELOC_ADD_EXTRA (p) -= pc_relocation;
  5188. #endif
  5189.       continue;
  5190.     }
  5191. #endif    
  5192. #endif
  5193.  
  5194.       relocation >>= RELOC_VALUE_RIGHTSHIFT(p);
  5195.  
  5196.       /* Unshifted mask for relocation */
  5197.       mask = 1 << RELOC_TARGET_BITSIZE(p) - 1;
  5198.       mask |= mask - 1;
  5199.       relocation &= mask;
  5200.  
  5201.       /* Shift everything up to where it's going to be used */
  5202.       relocation <<= RELOC_TARGET_BITPOS(p);
  5203.       mask <<= RELOC_TARGET_BITPOS(p);
  5204.  
  5205.       switch (RELOC_TARGET_SIZE(p))
  5206.     {
  5207.     case 0:
  5208.       if (RELOC_MEMORY_SUB_P(p))
  5209.         relocation -= mask & *(char *) (data + addr);
  5210.       else if (RELOC_MEMORY_ADD_P(p))
  5211.         relocation += mask & *(char *) (data + addr);
  5212.       *(char *) (data + addr) &= ~mask;
  5213.       *(char *) (data + addr) |= relocation;
  5214.       break;
  5215.  
  5216.         case 1:
  5217. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5218.       x = ((unsigned char *) (data + addr))[1]
  5219.        | (((unsigned char *) (data + addr))[0] << 8);
  5220. #endif
  5221. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5222.       x = ((unsigned char *) (data + addr))[0]
  5223.        | (((unsigned char *) (data + addr))[1] << 8);
  5224. #endif
  5225.       if (RELOC_MEMORY_SUB_P(p))
  5226.         relocation -= mask & x;
  5227.       else if (RELOC_MEMORY_ADD_P(p))
  5228.         relocation += mask & x;
  5229.       x &= ~mask;
  5230.       x |= relocation;
  5231. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5232.       ((unsigned char *) (data + addr))[1] = x;
  5233.       ((unsigned char *) (data + addr))[0] = x >> 8;
  5234. #endif
  5235. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5236.       ((unsigned char *) (data + addr))[0] = x;
  5237.       ((unsigned char *) (data + addr))[1] = x >> 8;
  5238. #endif
  5239.       break;
  5240.  
  5241.     case 2:
  5242. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5243.       x = ((unsigned char *) (data + addr))[3]
  5244.        | (((unsigned char *) (data + addr))[2] << 8)
  5245.        | (((unsigned char *) (data + addr))[1] << 16)
  5246.        | (((unsigned char *) (data + addr))[0] << 24);
  5247. #endif
  5248. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5249.       x = ((unsigned char *) (data + addr))[0]
  5250.        | (((unsigned char *) (data + addr))[1] << 8)
  5251.        | (((unsigned char *) (data + addr))[2] << 16)
  5252.        | (((unsigned char *) (data + addr))[3] << 24);
  5253. #endif
  5254.       if (RELOC_MEMORY_SUB_P(p))
  5255.         relocation -= mask & x;
  5256.       else if (RELOC_MEMORY_ADD_P(p))
  5257.         relocation += mask & x;
  5258.       x &= ~mask;
  5259.       x |= relocation;
  5260. #if TARGET_BYTE_ORDER==BIG_ENDIAN
  5261.       ((unsigned char *) (data + addr))[3] = x;
  5262.       ((unsigned char *) (data + addr))[2] = x >> 8;
  5263.       ((unsigned char *) (data + addr))[1] = x >> 16;
  5264.       ((unsigned char *) (data + addr))[0] = x >> 24;
  5265. #endif
  5266. #if TARGET_BYTE_ORDER==LITTLE_ENDIAN
  5267.       ((unsigned char *) (data + addr))[0] = x;
  5268.       ((unsigned char *) (data + addr))[1] = x >> 8;
  5269.       ((unsigned char *) (data + addr))[2] = x >> 16;
  5270.       ((unsigned char *) (data + addr))[3] = x >> 24;
  5271. #endif
  5272.       break;
  5273.  
  5274.     default:
  5275.       fatal_with_file ("Unimplemented relocation field length in ", entry);
  5276.     }
  5277.     }
  5278. }
  5279.  
  5280. /* For OUTPUT_RELOCATABLE only: write out the relocation,
  5281.    relocating the addresses-to-be-relocated.  */
  5282.  
  5283. void coptxtrel (), copdatrel ();
  5284.  
  5285. void
  5286. write_rel ()
  5287. {
  5288.   register int i;
  5289.   register int count = 0;
  5290.  
  5291.   if (trace_files)
  5292.     fprintf (stderr, "Writing text relocation:\n\n");
  5293.  
  5294.   /* Assign each global symbol a sequence number, giving the order
  5295.      in which `write_syms' will write it.
  5296.      This is so we can store the proper symbolnum fields
  5297.      in relocation entries we write.  */
  5298.  
  5299.   for (i = 0; i < TABSIZE; i++)
  5300.     {
  5301.       symbol *sp;
  5302.       for (sp = symtab[i]; sp; sp = sp->link)
  5303.     if (sp->referenced || sp->defined)
  5304.       {
  5305.         sp->def_count = count++;
  5306. #ifndef NeXT
  5307.         /* Leave room for the reference required by N_INDR, if
  5308.            necessary.  */
  5309.         if ((sp->defined & ~N_EXT) == N_INDR)
  5310.           count++;
  5311. #endif
  5312.       }
  5313.     }
  5314.   /* Correct, because if (OUTPUT_RELOCATABLE), we will also be writing
  5315.      whatever indirect blocks we have.  */
  5316. #ifndef NeXT
  5317.   if (count != defined_global_sym_count
  5318.       + undefined_global_sym_count + global_indirect_count)
  5319. #else
  5320.   if (count != defined_global_sym_count
  5321.       + undefined_global_sym_count)
  5322. #endif
  5323.     fatal ("internal error");
  5324.  
  5325.   /* Write out the relocations of all files, remembered from copy_text.  */
  5326.  
  5327.   lseek (outdesc, output_trel_offset, 0);
  5328.   each_full_file (coptxtrel, 0);
  5329.  
  5330.   if (trace_files)
  5331.     fprintf (stderr, "\nWriting data relocation:\n\n");
  5332.  
  5333.   lseek (outdesc, output_drel_offset, 0);
  5334.   each_full_file (copdatrel, 0);
  5335.  
  5336.   if (trace_files)
  5337.     fprintf (stderr, "\n");
  5338. }
  5339.  
  5340. void
  5341. coptxtrel (entry)
  5342.      struct file_entry *entry;
  5343. {
  5344.   register struct relocation_info *p, *end;
  5345.   register int reloc = entry->text_start_address - text_start;
  5346.  
  5347.   p = entry->textrel;
  5348.   end = (struct relocation_info *) (entry->text_reloc_size + (char *) p);
  5349.   while (p < end)
  5350.     {
  5351.       RELOC_ADDRESS(p) += reloc;
  5352.       if (RELOC_EXTERN_P(p))
  5353.     {
  5354.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5355.       symbol *symptr = ((symbol *)
  5356.                 (((struct nlist *)
  5357.                   (((char *)entry->symbols) + symindex))
  5358.                  ->n_un.n_name));
  5359.  
  5360.       if (symindex >= entry->syms_size)
  5361.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5362.  
  5363. #ifdef N_INDR
  5364.       /* Resolve indirection.  */
  5365.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5366.         symptr = (symbol *) symptr->value;
  5367. #endif
  5368.  
  5369.       /* If the symbol is now defined, change the external relocation
  5370.          to an internal one.  */
  5371.  
  5372.       if (symptr->defined)
  5373.         {
  5374.           RELOC_EXTERN_P(p) = 0;
  5375.           RELOC_SYMBOL(p) = (symptr->defined & ~N_EXT);
  5376. #ifdef RELOC_ADD_EXTRA
  5377.           /* If we aren't going to be adding in the value in
  5378.              memory on the next pass of the loader, then we need
  5379.          to add it in from the relocation entry.  Otherwise
  5380.              the work we did in this pass is lost.  */
  5381.           if (!RELOC_MEMORY_ADD_P(p))
  5382.         RELOC_ADD_EXTRA (p) += symptr->value;
  5383. #endif
  5384.         }
  5385.       else
  5386.         /* Debugger symbols come first, so have to start this
  5387.            after them.  */
  5388. #ifndef NeXT
  5389.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5390.                  - defined_global_sym_count
  5391.                  - undefined_global_sym_count
  5392.                  - global_indirect_count);
  5393. #else
  5394.           RELOC_SYMBOL(p) = (symptr->def_count + nsyms
  5395.                  - defined_global_sym_count
  5396.                  - undefined_global_sym_count);
  5397. #endif
  5398.     }
  5399.       p++;
  5400.     }
  5401.  
  5402. #ifdef MACH_O
  5403.   if (output_file_type == IS_MACH_O)
  5404.     generate_mach_o_relocations(entry->textrel,
  5405.                 entry->text_reloc_size / sizeof (struct relocation_info));
  5406. #else
  5407. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5408.     host_to_target_reloc_byte_order((struct relocation_info *) entry->textrel,
  5409.     entry->text_reloc_size/sizeof(struct relocation_info));
  5410. #endif
  5411. #endif
  5412.  
  5413.   mywrite (entry->textrel, 1, entry->text_reloc_size, outdesc);
  5414. }
  5415.  
  5416. void
  5417. copdatrel (entry)
  5418.      struct file_entry *entry;
  5419. {
  5420.   register struct relocation_info *p, *end;
  5421.   /* Relocate the address of the relocation.
  5422.      Old address is relative to start of the input file's data section.
  5423.      New address is relative to start of the output file's data section.
  5424.  
  5425.      So the amount we need to relocate it by is the offset of this
  5426.      input file's data section within the output file's data section.  */
  5427.   register int reloc = entry->data_start_address - data_start;
  5428.  
  5429.   p = entry->datarel;
  5430.   end = (struct relocation_info *) (entry->data_reloc_size + (char *) p);
  5431.   while (p < end)
  5432.     {
  5433.       RELOC_ADDRESS(p) += reloc;
  5434.       if (RELOC_EXTERN_P(p))
  5435.     {
  5436.       register int symindex = RELOC_SYMBOL(p) * sizeof (struct nlist);
  5437.       symbol *symptr = ((symbol *)
  5438.                 (((struct nlist *)
  5439.                   (((char *)entry->symbols) + symindex))
  5440.                  ->n_un.n_name));
  5441.       int symtype;
  5442.  
  5443.       if (symindex >= entry->syms_size)
  5444.         fatal_with_file ("relocation symbolnum out of range in ", entry);
  5445.  
  5446. #ifdef N_INDR
  5447.       /* Resolve indirection.  */
  5448.       if ((symptr->defined & ~N_EXT) == N_INDR)
  5449.         symptr = (symbol *) symptr->value;
  5450. #endif
  5451.  
  5452.       symtype = symptr->defined & ~N_EXT;
  5453.  
  5454.       if (force_common_definition
  5455.           || symtype == N_DATA || symtype == N_TEXT || symtype == N_ABS)
  5456.         {
  5457.           RELOC_EXTERN_P(p) = 0;
  5458.           RELOC_SYMBOL(p) = symtype;
  5459.         }
  5460.       else
  5461.         /* Debugger symbols come first, so have to start this
  5462.            after them.  */
  5463. #ifndef NeXT
  5464.         RELOC_SYMBOL(p)
  5465.           = (((symbol *)
  5466.           (((struct nlist *)
  5467.             (((char *)entry->symbols) + symindex))
  5468.            ->n_un.n_name))
  5469.          ->def_count
  5470.          + nsyms - defined_global_sym_count
  5471.          - undefined_global_sym_count
  5472.          - global_indirect_count);
  5473. #else
  5474.         RELOC_SYMBOL(p)
  5475.           = (((symbol *)
  5476.           (((struct nlist *)
  5477.             (((char *)entry->symbols) + symindex))
  5478.            ->n_un.n_name))
  5479.          ->def_count
  5480.          + nsyms - defined_global_sym_count
  5481.          - undefined_global_sym_count);
  5482. #endif
  5483.     }
  5484.       p++;
  5485.     }
  5486. #ifdef MACH_O
  5487.   if (output_file_type == IS_MACH_O)
  5488.     generate_mach_o_relocations(entry->datarel,
  5489.                 entry->data_reloc_size / sizeof (struct relocation_info));
  5490. #else
  5491. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5492.     host_to_target_reloc_byte_order((struct relocation_info *) entry->datarel,
  5493.     entry->data_reloc_size/sizeof(struct relocation_info));
  5494. #endif
  5495. #endif
  5496.  
  5497.   mywrite (entry->datarel, 1, entry->data_reloc_size, outdesc);
  5498. }
  5499.  
  5500. void write_file_syms ();
  5501. void write_string_table ();
  5502.  
  5503. /* Total size of string table strings allocated so far,
  5504.    including strings in `strtab_vector'.  */
  5505. int strtab_size;
  5506.  
  5507. /* Vector whose elements are strings to be added to the string table.  */
  5508. char **strtab_vector;
  5509.  
  5510. /* Vector whose elements are the lengths of those strings.  */
  5511. int *strtab_lens;
  5512.  
  5513. /* Index in `strtab_vector' at which the next string will be stored.  */
  5514. int strtab_index;
  5515.  
  5516. /* Add the string NAME to the output file string table.
  5517.    Record it in `strtab_vector' to be output later.
  5518.    Return the index within the string table that this string will have.  */
  5519.  
  5520. int
  5521. assign_string_table_index (name)
  5522.      char *name;
  5523. {
  5524.   register int index = strtab_size;
  5525.   register int len = strlen (name) + 1;
  5526.  
  5527.   strtab_size += len;
  5528.   strtab_vector[strtab_index] = name;
  5529.   strtab_lens[strtab_index++] = len;
  5530.  
  5531.   return index;
  5532. }
  5533.  
  5534. FILE *outstream = (FILE *) 0;
  5535.  
  5536. /* Write the contents of `strtab_vector' into the string table.
  5537.    This is done once for each file's local&debugger symbols
  5538.    and once for the global symbols.  */
  5539.  
  5540. void
  5541. write_string_table ()
  5542. {
  5543.   register int i;
  5544.  
  5545.   lseek (outdesc, output_strs_offset + output_strs_size, 0);
  5546.  
  5547.   if (!outstream)
  5548.     outstream = fdopen (outdesc, "w");
  5549.  
  5550.   for (i = 0; i < strtab_index; i++)
  5551.     {
  5552.       fwrite (strtab_vector[i], 1, strtab_lens[i], outstream);
  5553.       output_strs_size += strtab_lens[i];
  5554.     }
  5555.  
  5556.   fflush (outstream);
  5557.  
  5558.   /* Report I/O error such as disk full.  */
  5559.   if (ferror (outstream))
  5560.     perror_name (output_filename);
  5561. }
  5562.  
  5563. /* Write the symbol table and string table of the output file.  */
  5564.  
  5565. void
  5566. write_syms ()
  5567. {
  5568.   /* Number of symbols written so far.  */
  5569.   int syms_written = 0;
  5570.   register int i;
  5571.   register symbol *sp;
  5572.  
  5573.   /* Buffer big enough for all the global symbols.  One
  5574.      extra struct for each indirect symbol to hold the extra reference
  5575.      following. */
  5576.   struct nlist *buf
  5577. #if TARGET_MACHINE==TARGET_NeXT
  5578.     = (struct nlist *) alloca ((defined_global_sym_count
  5579.                 + undefined_global_sym_count
  5580.                 + global_indirect_count)
  5581.                    * sizeof (struct nlist));
  5582. #else
  5583.     = (struct nlist *) alloca ((defined_global_sym_count
  5584.                 + undefined_global_sym_count)
  5585.                    * sizeof (struct nlist));
  5586. #endif
  5587.   /* Pointer for storing into BUF.  */
  5588.   register struct nlist *bufp = buf;
  5589.  
  5590.   /* Size of string table includes the bytes that store the size.  */
  5591.   strtab_size = sizeof strtab_size;
  5592.  
  5593.   output_syms_size = 0;
  5594.   output_strs_size = strtab_size;
  5595.  
  5596.   if (strip_symbols == STRIP_ALL)
  5597.     return;
  5598.  
  5599.   /* Write the local symbols defined by the various files.  */
  5600.  
  5601.   each_file (write_file_syms, &syms_written);
  5602.   file_close ();
  5603.  
  5604.   /* Now write out the global symbols.  */
  5605.  
  5606.   /* Allocate two vectors that record the data to generate the string
  5607.      table from the global symbols written so far.  This must include
  5608.      extra space for the references following indirect outputs. */
  5609.  
  5610.   strtab_vector = (char **) alloca ((num_hash_tab_syms
  5611.                      + global_indirect_count) * sizeof (char *));
  5612.   strtab_lens = (int *) alloca ((num_hash_tab_syms
  5613.                  + global_indirect_count) * sizeof (int));
  5614.   strtab_index = 0;
  5615.  
  5616.   /* Scan the symbol hash table, bucket by bucket.  */
  5617.  
  5618.   for (i = 0; i < TABSIZE; i++)
  5619.     for (sp = symtab[i]; sp; sp = sp->link)
  5620.       {
  5621.     struct nlist nl;
  5622.  
  5623. #ifdef N_SECT
  5624.     nl.n_sect = 0;
  5625. #else
  5626.     nl.n_other = 0;
  5627. #endif
  5628.     nl.n_desc = 0;
  5629.  
  5630.     /* Compute a `struct nlist' for the symbol.  */
  5631.  
  5632.     if (sp->defined || sp->referenced)
  5633.       {
  5634.         /* common condition needs to be before undefined condition */
  5635.         /* because unallocated commons are set undefined in */
  5636.         /* digest_symbols */
  5637.         if (sp->defined > 1) /* defined with known type */
  5638.           {
  5639.         /* If the target of an indirect symbol has been
  5640.            defined and we are outputting an executable,
  5641.            resolve the indirection; it's no longer needed */
  5642.         if (output_style != OUTPUT_RELOCATABLE
  5643.             && ((sp->defined & ~N_EXT) == N_INDR)
  5644.             && (((symbol *) sp->value)->defined > 1))
  5645.           {
  5646.             symbol *newsp = (symbol *) sp->value;
  5647.             nl.n_type = newsp->defined;
  5648.             nl.n_value = newsp->value;
  5649.           }
  5650.         else
  5651.           {
  5652.             nl.n_type = sp->defined;
  5653.             if (sp->defined != (N_INDR | N_EXT))
  5654.               nl.n_value = sp->value;
  5655.             else
  5656.               nl.n_value = 0;
  5657.           }
  5658.           }
  5659.         else if (sp->max_common_size) /* defined as common but not allocated. */
  5660.           {
  5661.         /* happens only with -r and not -d */
  5662.         /* write out a common definition */
  5663.         nl.n_type = N_UNDF | N_EXT;
  5664.         nl.n_value = sp->max_common_size;
  5665.           }
  5666.         else if (!sp->defined)          /* undefined -- legit only if -r */
  5667.           {
  5668.         nl.n_type = N_UNDF | N_EXT;
  5669.         nl.n_value = 0;
  5670.           }
  5671.         else
  5672.           fatal ("internal error: %s defined in mysterious way", sp->name);
  5673.  
  5674.         /* Allocate string table space for the symbol name.  */
  5675.  
  5676.         nl.n_un.n_strx = assign_string_table_index (sp->name);
  5677.  
  5678.         /* Output to the buffer and count it.  */
  5679.  
  5680.         *bufp++ = nl;
  5681.         syms_written++;
  5682.         if (nl.n_type == (N_INDR | N_EXT))
  5683. #ifndef NeXT
  5684.           {
  5685.         struct nlist xtra_ref;
  5686.         xtra_ref.n_type == N_EXT | N_UNDF;
  5687.         xtra_ref.n_un.n_strx
  5688.           = assign_string_table_index (((symbol *) sp->value)->name);
  5689. #ifdef N_SECT
  5690.         xtra_ref.n_sect = 0;
  5691. #else
  5692.         xtra_ref.n_other = 0;
  5693. #endif
  5694.         xtra_ref.n_desc = 0;
  5695.         xtra_ref.n_value = 0;
  5696.         *bufp++ = xtra_ref;
  5697.         syms_written++;
  5698.           }
  5699. #else
  5700.         nl.n_value = assign_string_table_index (((symbol *) sp->value)->name);
  5701. #endif
  5702.       }
  5703.       }
  5704.  
  5705. #ifdef MACH_O
  5706.   if (output_file_type == IS_MACH_O)
  5707.     generate_mach_o_symbols(buf, bufp - buf);
  5708. #endif
  5709.  
  5710.   /* Output the buffer full of `struct nlist's.  */
  5711.  
  5712.   lseek (outdesc, output_syms_offset + output_syms_size, 0);
  5713. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5714.   {
  5715.     int i;
  5716.  
  5717.     for (i = 0; i < bufp - buf; ++i)
  5718.       {
  5719.         fix_byte_order(&buf[i].n_un.n_name, sizeof(buf->n_un.n_name));
  5720.     fix_byte_order(&buf[i].n_desc, sizeof(buf->n_desc));
  5721.     fix_byte_order(&buf[i].n_value, sizeof(buf->n_value));
  5722.       }
  5723.   }
  5724. #endif
  5725.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5726.   output_syms_size += sizeof (struct nlist) * (bufp - buf);
  5727.  
  5728.   if (syms_written != nsyms)
  5729.     fatal ("internal error: wrong number of symbols written into output file", 0);
  5730.  
  5731.   /* Now the total string table size is known, so write it into the
  5732.      first word of the string table.  */
  5733.  
  5734.   lseek (outdesc, output_strs_offset, 0);
  5735.  
  5736. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5737.   fix_byte_order(&strtab_size, sizeof(strtab_size));
  5738. #endif
  5739.  
  5740.   mywrite (&strtab_size, sizeof (int), 1, outdesc);
  5741.  
  5742.   /* Write the strings for the global symbols.  */
  5743.  
  5744.   write_string_table ();
  5745. }
  5746.  
  5747. /* Write the local and debugger symbols of file ENTRY.
  5748.    Increment *SYMS_WRITTEN_ADDR for each symbol that is written.  */
  5749.  
  5750. /* Note that we do not combine identical names of local symbols.
  5751.    dbx or gdb would be confused if we did that.  */
  5752.  
  5753. void
  5754. write_file_syms (entry, syms_written_addr)
  5755.      struct file_entry *entry;
  5756.      int *syms_written_addr;
  5757. {
  5758.   register struct nlist *p = entry->symbols;
  5759.   register struct nlist *end = p + entry->syms_size / sizeof (struct nlist);
  5760.  
  5761.   /* Buffer to accumulate all the syms before writing them.
  5762.      It has one extra slot for the local symbol we generate here.  */
  5763.   struct nlist *buf
  5764.     = (struct nlist *) alloca (entry->syms_size + sizeof (struct nlist));
  5765.   register struct nlist *bufp = buf;
  5766.  
  5767.   /* Upper bound on number of syms to be written here.  */
  5768.   int max_syms = (entry->syms_size / sizeof (struct nlist)) + 1;
  5769.  
  5770.   /* Make tables that record, for each symbol, its name and its name's length.
  5771.      The elements are filled in by `assign_string_table_index'.  */
  5772.  
  5773.   strtab_vector = (char **) alloca (max_syms * sizeof (char *));
  5774.   strtab_lens = (int *) alloca (max_syms * sizeof (int));
  5775.   strtab_index = 0;
  5776.  
  5777.   /* Generate a local symbol for the start of this file's text.  */
  5778.  
  5779.   if (discard_locals != DISCARD_ALL)
  5780.     {
  5781.       struct nlist nl;
  5782.  
  5783. #if TARGET==TARGET_SEQUENT      
  5784.       nl.n_type = N_FN;
  5785. #else      
  5786.       nl.n_type = N_TEXT;
  5787. #endif
  5788.       nl.n_un.n_strx = assign_string_table_index (entry->local_sym_name);
  5789.       nl.n_value = entry->text_start_address;
  5790.       nl.n_desc = 0;
  5791. #ifdef N_SECT
  5792.       nl.n_sect = 0;
  5793. #else
  5794.       nl.n_other = 0;
  5795. #endif
  5796.       *bufp++ = nl;
  5797.       (*syms_written_addr)++;
  5798.       entry->local_syms_offset = *syms_written_addr * sizeof (struct nlist);
  5799.     }
  5800.  
  5801.   /* Read the file's string table.  */
  5802.  
  5803.   entry->strings = (char *) alloca (entry->strs_size);
  5804.   read_entry_strings (file_open (entry), entry);
  5805.  
  5806.   for (; p < end; p++)
  5807.     {
  5808.       register int type = p->n_type;
  5809.       register int write = 0;
  5810.  
  5811.       /* WRITE gets 1 for a non-global symbol that should be written.  */
  5812.  
  5813.  
  5814.       if (SET_ELEMENT_P (type))    /* This occurs even if global.  These */
  5815.                 /* types of symbols are never written */
  5816.                 /* globally, though they are stored */
  5817.                 /* globally.  */
  5818.         write = output_style == OUTPUT_RELOCATABLE;
  5819.       else if (!(type & (N_STAB | N_EXT)))
  5820.         /* ordinary local symbol */
  5821.     write = ((discard_locals != DISCARD_ALL)
  5822.          && !(discard_locals == DISCARD_L &&
  5823.               (p->n_un.n_strx + entry->strings)[0] == LPREFIX)
  5824.          && type != N_WARNING);
  5825.       else if (!(type & N_EXT))
  5826.     /* debugger symbol */
  5827.         write = (strip_symbols == STRIP_NONE);
  5828.  
  5829.       if (write)
  5830.     {
  5831.       /* If this symbol has a name,
  5832.          allocate space for it in the output string table.  */
  5833.  
  5834.       if (p->n_un.n_strx)
  5835.         p->n_un.n_strx = assign_string_table_index (p->n_un.n_strx
  5836.                             + entry->strings);
  5837.  
  5838.       /* Output this symbol to the buffer and count it.  */
  5839.  
  5840.       *bufp++ = *p;
  5841.       (*syms_written_addr)++;
  5842.     }
  5843.     }
  5844.  
  5845. #ifdef MACH_O
  5846.   if (output_file_type == IS_MACH_O)
  5847.     generate_mach_o_symbols(buf, bufp - buf);
  5848. #else
  5849. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5850.   {
  5851.     int i;
  5852.  
  5853.     for (i = 0; i < bufp - buf; ++i)
  5854.       {
  5855.     fix_byte_order(&buf[i].n_un.n_name, sizeof(buf->n_un.n_name));
  5856.     fix_byte_order(&buf[i].n_desc, sizeof(buf->n_desc));
  5857.     fix_byte_order(&buf[i].n_value, sizeof(buf->n_value));
  5858.       }
  5859.   }
  5860. #endif
  5861. #endif
  5862.  
  5863.   /* All the symbols are now in BUF; write them.  */
  5864.  
  5865.   lseek (outdesc, output_syms_offset + output_syms_size, 0);
  5866.   mywrite (buf, sizeof (struct nlist), bufp - buf, outdesc);
  5867.   output_syms_size += sizeof (struct nlist) * (bufp - buf);
  5868.  
  5869.   /* Write the string-table data for the symbols just written,
  5870.      using the data in vectors `strtab_vector' and `strtab_lens'.  */
  5871.  
  5872.   write_string_table ();
  5873.   entry->strings = 0;        /* Since it will dissapear anyway.  */
  5874. }
  5875.  
  5876. /* Copy any GDB symbol segments from the input files to the output file.
  5877.    The contents of the symbol segment is copied without change
  5878.    except that we store some information into the beginning of it.  */
  5879.  
  5880. void write_file_symseg ();
  5881.  
  5882. void
  5883. write_symsegs ()
  5884. {
  5885.   lseek (outdesc, output_symseg_offset, 0);
  5886.   each_file (write_file_symseg, 0);
  5887. }
  5888.  
  5889. void
  5890. write_file_symseg (entry)
  5891.      struct file_entry *entry;
  5892. {
  5893.   char buffer[4096];
  5894.   struct symbol_root root;
  5895.   int indesc, len, total;
  5896.  
  5897.   if (entry->symseg_size == 0)
  5898.     return;
  5899.  
  5900.   output_symseg_size += entry->symseg_size;
  5901.  
  5902.   /* This entry has a symbol segment.  Read the root of the segment.  */
  5903.  
  5904.   indesc = file_open (entry);
  5905.   lseek (indesc, entry->symseg_offset + entry->starting_offset, 0);
  5906.   if (sizeof root != read (indesc, &root, sizeof root))
  5907.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  5908.  
  5909. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5910.   fix_symbol_root_byte_order(&root);
  5911. #endif
  5912.  
  5913.   /* Store some relocation info into the root.  */
  5914.  
  5915.   root.ldsymoff = entry->local_syms_offset;
  5916.   root.textrel = entry->text_start_address - entry->orig_text_address;
  5917.   root.datarel = entry->data_start_address - entry->orig_data_address;
  5918.   root.bssrel = entry->bss_start_address - entry->orig_bss_address;
  5919.   root.databeg = entry->data_start_address - root.datarel;
  5920.   root.bssbeg = entry->bss_start_address - root.bssrel;
  5921.  
  5922.   /* Write the modified root into the output file.  */
  5923.  
  5924. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  5925.   fix_symbol_root_byte_order(&root);
  5926. #endif
  5927.   mywrite (&root, sizeof root, 1, outdesc);
  5928.  
  5929.   /* Copy the rest of the symbol segment unchanged.  */
  5930.  
  5931.   total = entry->symseg_size - sizeof root;
  5932.  
  5933.   while (total > 0)
  5934.     {
  5935.       len = read (indesc, buffer, min (sizeof buffer, total));
  5936.  
  5937.       if (len != min (sizeof buffer, total))
  5938.     fatal_with_file ("premature end of file in symbol segment of ", entry);
  5939.       total -= len;
  5940.       mywrite (buffer, len, 1, outdesc);
  5941.     }
  5942.  
  5943.   file_close ();
  5944. }
  5945.  
  5946. /* Define a special symbol (etext, edata, or end).  NAME is the
  5947.    name of the symbol, with a leading underscore (whether or not this
  5948.    system uses such underscores).  TYPE is its type (e.g. N_DATA | N_EXT).
  5949.    Store a symbol * for the symbol in *SYM if SYM is non-NULL.  */
  5950. static void
  5951. symbol_define (name, type, sym)
  5952.      /* const */ char *name;
  5953.      int type;
  5954.      symbol **sym;
  5955. {
  5956.   symbol *thesym;
  5957.  
  5958. #if defined(nounderscore)
  5959.   /* Skip the leading underscore.  */
  5960.   name++;
  5961. #endif
  5962.  
  5963.   thesym = getsym (name);
  5964.   if (thesym->defined)
  5965.     {
  5966.       /* The symbol is defined in some input file.  Don't mess with it.  */
  5967.       if (sym)
  5968.     *sym = 0;
  5969.     }
  5970.   else
  5971.     {
  5972.       if (thesym->referenced)
  5973.     /* The symbol was not defined, and we are defining it now.  */
  5974.     undefined_global_sym_count--;
  5975.       thesym->defined = type;
  5976.       thesym->referenced = 1;
  5977.       if (sym)
  5978.     *sym = thesym;
  5979.     }
  5980. }
  5981.  
  5982. /* Create the symbol table entries for `etext', `edata' and `end'.  */
  5983.  
  5984. void
  5985. symtab_init ()
  5986. {
  5987.   symbol_define ("_edata", N_DATA | N_EXT, &edata_symbol);
  5988.   symbol_define ("_etext", N_TEXT | N_EXT, &etext_symbol);
  5989.   symbol_define ("_end", N_BSS | N_EXT, &end_symbol);
  5990.  
  5991.   /* Either _edata or __edata (C names) is OK as far as ANSI is concerned
  5992.      (see section 4.1.2.1).  In general, it is best to use __foo and
  5993.      not worry about the confusing rules for the _foo namespace.
  5994.      But HPUX 7.0 uses _edata, so we might as weel be consistent.  */
  5995.   symbol_define ("__edata", N_DATA | N_EXT, &edata_symbol_alt);
  5996.   symbol_define ("__etext", N_TEXT | N_EXT, &etext_symbol_alt);
  5997.   symbol_define ("__end", N_BSS | N_EXT, &end_symbol_alt);
  5998.  
  5999. #if TARGET_MACHINE==TARGET_SUN4 || TARGET_MACHINE==TARGET_SUN3 || TARGET_MACHINE==TARGET_SUN2
  6000.   {
  6001.     symbol *dynamic_symbol;
  6002.     symbol_define ("__DYNAMIC", N_ABS | N_EXT, &dynamic_symbol);
  6003.     if (dynamic_symbol)
  6004.       dynamic_symbol->value = 0;
  6005.   }
  6006. #endif
  6007. #if TARGET_MACHINE==TARGET_SEQUENT
  6008.   {
  6009.     symbol *i387_flt_symbol;
  6010.     symbol_define ("_387_flt", N_ABS | N_EXT, &i387_flt_symbol);
  6011.     if (i387_flt_symbol)
  6012.       i387_flt_symbol->value = 0;
  6013.   }
  6014. #endif
  6015. #if TARGET_MACHINE==TARGET_NeXT
  6016.   {
  6017.     symbol *shlib_init_symbol;
  6018.     symbol_define ("__shared_library_initialization", N_UNDF | N_EXT, &shlib_init_symbol);
  6019.     if (shlib_init_symbol)
  6020.       shlib_init_symbol->max_common_size = sizeof (long int);
  6021.   }
  6022. #endif
  6023. }
  6024.  
  6025. /* Compute the hash code for symbol name KEY.  */
  6026.  
  6027. int
  6028. hash_string (key)
  6029.      char *key;
  6030. {
  6031.   register char *cp;
  6032.   register int k;
  6033.  
  6034.   cp = key;
  6035.   k = 0;
  6036.   while (*cp)
  6037.     k = (((k << 1) + (k >> 14)) ^ (*cp++)) & 0x3fff;
  6038.  
  6039.   return k;
  6040. }
  6041.  
  6042. /* Get the symbol table entry for the global symbol named KEY.
  6043.    Create one if there is none.  */
  6044.  
  6045. symbol *
  6046. getsym (key)
  6047.      char *key;
  6048. {
  6049.   register int hashval;
  6050.   register symbol *bp;
  6051.  
  6052.   /* Determine the proper bucket.  */
  6053.  
  6054.   hashval = hash_string (key) % TABSIZE;
  6055.  
  6056.   /* Search the bucket.  */
  6057.  
  6058.   for (bp = symtab[hashval]; bp; bp = bp->link)
  6059.     if (! strcmp (key, bp->name))
  6060.       return bp;
  6061.  
  6062.   /* Nothing was found; create a new symbol table entry.  */
  6063.  
  6064.   bp = (symbol *) xmalloc (sizeof (symbol));
  6065.   bp->refs = 0;
  6066.   bp->name = (char *) xmalloc (strlen (key) + 1);
  6067.   strcpy (bp->name, key);
  6068.   bp->defined = 0;
  6069.   bp->referenced = 0;
  6070.   bp->trace = 0;
  6071.   bp->value = 0;
  6072.   bp->max_common_size = 0;
  6073.   bp->warning = 0;
  6074.   bp->undef_refs = 0;
  6075.   bp->multiply_defined = 0;
  6076.  
  6077.   /* Add the entry to the bucket.  */
  6078.  
  6079.   bp->link = symtab[hashval];
  6080.   symtab[hashval] = bp;
  6081.  
  6082.   ++num_hash_tab_syms;
  6083.  
  6084.   return bp;
  6085. }
  6086.  
  6087. /* Like `getsym' but return 0 if the symbol is not already known.  */
  6088.  
  6089. symbol *
  6090. getsym_soft (key)
  6091.      char *key;
  6092. {
  6093.   register int hashval;
  6094.   register symbol *bp;
  6095.  
  6096.   /* Determine which bucket.  */
  6097.  
  6098.   hashval = hash_string (key) % TABSIZE;
  6099.  
  6100.   /* Search the bucket.  */
  6101.  
  6102.   for (bp = symtab[hashval]; bp; bp = bp->link)
  6103.     if (! strcmp (key, bp->name))
  6104.       return bp;
  6105.  
  6106.   return 0;
  6107. }
  6108.  
  6109. /* Report a usage error.
  6110.    Like fatal except prints a usage summary.  */
  6111.  
  6112. void
  6113. usage (string, arg)
  6114.      char *string, *arg;
  6115. {
  6116.   if (string)
  6117.     {
  6118.       fprintf (stderr, "%s: ", progname);
  6119.       fprintf (stderr, string, arg);
  6120.       fprintf (stderr, "\n");
  6121.     }
  6122.   fprintf (stderr, "\
  6123. Usage: %s \n\
  6124.        [-d] [-dc] [-dp] [-e symbol] [-l lib] [-n] [-noinhibit-exec]\n\
  6125.        [-nostdlib] [-o file] [-r] [-s] [-t] [-u symbol] [-x] [-y symbol]\n\
  6126.        [-z] [-A file] [-Bstatic] [-D size] [-L libdir] [-M] [-N]\n\
  6127.        [-S] [-T[{text,data}] addr] [-V prefix] [-X] [file...]\n",
  6128.        progname);
  6129.   exit (1);
  6130. }
  6131.  
  6132. /* Report a fatal error.
  6133.    STRING is a printf format string and ARG is one arg for it.  */
  6134.  
  6135. void
  6136. fatal (string, arg)
  6137.      char *string, *arg;
  6138. {
  6139.   fprintf (stderr, "%s: ", progname);
  6140.   fprintf (stderr, string, arg);
  6141.   fprintf (stderr, "\n");
  6142.   exit (1);
  6143. }
  6144.  
  6145. /* Report a fatal error.  The error message is STRING
  6146.    followed by the filename of ENTRY.  */
  6147.  
  6148. void
  6149. fatal_with_file (string, entry)
  6150.      char *string;
  6151.      struct file_entry *entry;
  6152. {
  6153.   fprintf (stderr, "%s: ", progname);
  6154.   fprintf (stderr, string);
  6155.   print_file_name (entry, stderr);
  6156.   fprintf (stderr, "\n");
  6157.   exit (1);
  6158. }
  6159.  
  6160. /* Report a fatal error using the message for the last failed system call,
  6161.    followed by the string NAME.  */
  6162.  
  6163. void
  6164. perror_name (name)
  6165.      char *name;
  6166. {
  6167.   extern int errno, sys_nerr;
  6168.   extern char *sys_errlist[];
  6169.   char *s;
  6170.  
  6171.   if (errno < sys_nerr)
  6172.     s = concat ("", sys_errlist[errno], " for %s");
  6173.   else
  6174.     s = "cannot open %s";
  6175.   fatal (s, name);
  6176. }
  6177.  
  6178. /* Report a fatal error using the message for the last failed system call,
  6179.    followed by the name of file ENTRY.  */
  6180.  
  6181. void
  6182. perror_file (entry)
  6183.      struct file_entry *entry;
  6184. {
  6185.   extern int errno, sys_nerr;
  6186.   extern char *sys_errlist[];
  6187.   char *s;
  6188.  
  6189.   if (errno < sys_nerr)
  6190.     s = concat ("", sys_errlist[errno], " for ");
  6191.   else
  6192.     s = "cannot open ";
  6193.   fatal_with_file (s, entry);
  6194. }
  6195.  
  6196. /* Report a nonfatal error.
  6197.    STRING is a format for printf, and ARG1 ... ARG3 are args for it.  */
  6198.  
  6199. void
  6200. error (string, arg1, arg2, arg3)
  6201.      char *string, *arg1, *arg2, *arg3;
  6202. {
  6203.   fprintf (stderr, "%s: ", progname);
  6204.   fprintf (stderr, string, arg1, arg2, arg3);
  6205.   fprintf (stderr, "\n");
  6206. }
  6207.  
  6208.  
  6209. /* Output COUNT*ELTSIZE bytes of data at BUF
  6210.    to the descriptor DESC.  */
  6211.  
  6212. void
  6213. mywrite (buf, count, eltsize, desc)
  6214.      char *buf;
  6215.      int count;
  6216.      int eltsize;
  6217.      int desc;
  6218. {
  6219.   register int val;
  6220.   register int bytes = count * eltsize;
  6221.  
  6222.   while (bytes > 0)
  6223.     {
  6224.       val = write (desc, buf, bytes);
  6225.       if (val <= 0)
  6226.     perror_name (output_filename);
  6227.       buf += val;
  6228.       bytes -= val;
  6229.     }
  6230. }
  6231.  
  6232. /* Output PADDING zero-bytes to descriptor OUTDESC.
  6233.    PADDING may be negative; in that case, do nothing.  */
  6234.  
  6235. void
  6236. padfile (padding, outdesc)
  6237.      int padding;
  6238.      int outdesc;
  6239. {
  6240.   register char *buf;
  6241.   if (padding <= 0)
  6242.     return;
  6243.  
  6244.   buf = (char *) alloca (padding);
  6245.   bzero (buf, padding);
  6246.   mywrite (buf, padding, 1, outdesc);
  6247. }
  6248.  
  6249. /* Return a newly-allocated string
  6250.    whose contents concatenate the strings S1, S2, S3.  */
  6251.  
  6252. char *
  6253. concat (s1, s2, s3)
  6254.      char *s1, *s2, *s3;
  6255. {
  6256.   register int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
  6257.   register char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
  6258.  
  6259.   strcpy (result, s1);
  6260.   strcpy (result + len1, s2);
  6261.   strcpy (result + len1 + len2, s3);
  6262.   result[len1 + len2 + len3] = 0;
  6263.  
  6264.   return result;
  6265. }
  6266.  
  6267. /* Parse the string ARG using scanf format FORMAT, and return the result.
  6268.    If it does not parse, report fatal error
  6269.    generating the error message using format string ERROR and ARG as arg.  */
  6270.  
  6271. int
  6272. parse (arg, format, error)
  6273.      char *arg, *format;
  6274. {
  6275.   int x;
  6276.   if (1 != sscanf (arg, format, &x))
  6277.     fatal (error, arg);
  6278.   return x;
  6279. }
  6280.  
  6281. /* Like malloc but get fatal error if memory is exhausted.  */
  6282.  
  6283. char *
  6284. xmalloc (size)
  6285.      int size;
  6286. {
  6287.   register char *result = malloc (size);
  6288.   if (!result)
  6289.     fatal ("virtual memory exhausted", 0);
  6290.   return result;
  6291. }
  6292.  
  6293. /* Like realloc but get fatal error if memory is exhausted.  */
  6294.  
  6295. char *
  6296. xrealloc (ptr, size)
  6297.      char *ptr;
  6298.      int size;
  6299. {
  6300.   register char *result = realloc (ptr, size);
  6301.   if (!result)
  6302.     fatal ("virtual memory exhausted", 0);
  6303.   return result;
  6304. }
  6305.  
  6306. #ifdef USG
  6307.  
  6308. void
  6309. bzero (p, n)
  6310.      char *p;
  6311. {
  6312.   memset (p, 0, n);
  6313. }
  6314.  
  6315. void
  6316. bcopy (from, to, n)
  6317.      char *from, *to;
  6318. {
  6319.   memcpy (to, from, n);
  6320. }
  6321.  
  6322. getpagesize ()
  6323. {
  6324.   return (4096);
  6325. }
  6326.  
  6327. #endif
  6328.  
  6329.  
  6330. #if HOST_BYTE_ORDER != TARGET_BYTE_ORDER
  6331.  
  6332. static void
  6333. fix_byte_order(p, n)
  6334.     char *p;
  6335.     int n;
  6336. {
  6337.     char t;
  6338.  
  6339.     switch (n) {
  6340.  
  6341.     case 1:
  6342.     return;
  6343.  
  6344.     case 2:
  6345.     t = p[0];
  6346.     p[0] = p[1];
  6347.     p[1] = t;
  6348.     return;
  6349.  
  6350.     case 4:
  6351.     t = p[0];
  6352.     p[0] = p[3];
  6353.     p[3] = t;
  6354.     t = p[1];
  6355.     p[1] = p[2];
  6356.     p[2] = t;
  6357.     return;
  6358.  
  6359.     default:
  6360.     fatal("Internal Error in fix_byte_order, n = %d\n", 0);
  6361.     }
  6362. }
  6363.  
  6364. static void
  6365. fix_exec_header_byte_order(execP)
  6366.     struct exec *execP;
  6367. {
  6368.  
  6369. #if TARGET_MACHINE==TARGET_SUN4
  6370.     if (N_BADMAG(*execP)) {
  6371.     u_char c = * (u_char *) execP;
  6372.     execP->a_dynamic = c & 1;
  6373.     execP->a_toolversion = c >> 1;
  6374.     } else {
  6375.     u_char c = execP->a_toolversion | (execP->a_dynamic << 7);
  6376.     * (u_char *) execP = c;
  6377.     }
  6378. #elif TARGET_MACHINE!=TARGET_SEQUENT
  6379.     fix_byte_order(&execP->a_machtype, sizeof(execP->a_machtype));
  6380. #endif
  6381.     fix_byte_order(&execP->a_magic,    sizeof(execP->a_magic));
  6382.     fix_byte_order(&execP->a_text,     sizeof(execP->a_text));
  6383.     fix_byte_order(&execP->a_data,     sizeof(execP->a_data));
  6384.     fix_byte_order(&execP->a_bss,      sizeof(execP->a_bss));
  6385.     fix_byte_order(&execP->a_syms,     sizeof(execP->a_syms));
  6386.     fix_byte_order(&execP->a_entry,    sizeof(execP->a_entry));
  6387.     fix_byte_order(&execP->a_trsize,   sizeof(execP->a_trsize));
  6388.     fix_byte_order(&execP->a_drsize,   sizeof(execP->a_drsize));
  6389.     return;
  6390. }
  6391.  
  6392. static void
  6393. fix_symbol_byte_order(p, size)
  6394.     struct nlist *p;
  6395.     int size;
  6396. {
  6397.     int n;
  6398.  
  6399.     for (n = size / sizeof(*p); --n >= 0; ++p) {
  6400.     fix_byte_order(&p->n_un, sizeof(p->n_un));
  6401.     fix_byte_order(&p->n_desc, sizeof(p->n_desc));
  6402.     fix_byte_order(&p->n_value, sizeof(p->n_value));
  6403.     }
  6404.     return;
  6405. }
  6406.  
  6407. static void
  6408. target_to_host_reloc_byte_order(relocP, nrelocs)
  6409.     struct relocation_info *relocP;
  6410.     int nrelocs;
  6411. {
  6412.     u_char c[4];
  6413.  
  6414. #if TARGET_BYTE_ORDER==BIG_ENDIAN && HOST_BYTE_ORDER==LITTLE_ENDIAN
  6415.     for (; --nrelocs >= 0; ++relocP) {
  6416.     fix_byte_order(&relocP->r_address, sizeof(relocP->r_address));
  6417.     c[0] = ((u_char *) relocP)[4];
  6418.     c[1] = ((u_char *) relocP)[5];
  6419.     c[2] = ((u_char *) relocP)[6];
  6420.     c[3] = ((u_char *) relocP)[7];
  6421.     ((u_long *) relocP)[1] = 0;
  6422. #if TARGET_MACHINE==TARGET_SUN4
  6423.     relocP->r_index = (c[0] << 16) | (c[1] << 8) | c[2];
  6424.     relocP->r_type = (enum reloc_type) (c[3] & 0x1f);
  6425.     relocP->r_extern = (c[3] & 0x80) >> 7;
  6426.     fix_byte_order(&relocP->r_addend, sizeof(relocP->r_addend));
  6427. #else
  6428.     relocP->r_symbolnum = (c[0] << 16) | (c[1] << 8) | c[2];
  6429.     relocP->r_pcrel = (c[3] >> 7) & 1;
  6430.     relocP->r_length = (c[3] >> 5) & 3;
  6431.     relocP->r_extern = (c[3] >> 4) & 1;
  6432. #endif
  6433.     }
  6434. #endif
  6435.     return;
  6436. }
  6437.  
  6438. static void
  6439. host_to_target_reloc_byte_order(relocP, nrelocs)
  6440.     struct relocation_info *relocP;
  6441.     int nrelocs;
  6442. {
  6443.     u_char c[4];
  6444.  
  6445. #if TARGET_BYTE_ORDER==BIG_ENDIAN && HOST_BYTE_ORDER==LITTLE_ENDIAN
  6446.     for (; --nrelocs >= 0; ++relocP) {
  6447.     fix_byte_order(&relocP->r_address, sizeof(relocP->r_address));
  6448. #if TARGET_MACHINE==TARGET_SUN4
  6449.     c[0] = (relocP->r_index >> 16);
  6450.     c[1] = (relocP->r_index >> 8);
  6451.     c[2] = relocP->r_index;
  6452.     c[3] = (u_char) relocP->r_type | (relocP->r_extern << 7);
  6453.     fix_byte_order(&relocP->r_addend, sizeof(relocP->r_addend));
  6454. #else
  6455.     c[0] = (relocP->r_symbolnum >> 16);
  6456.     c[1] = (relocP->r_symbolnum >> 8);
  6457.     c[2] = relocP->r_symbolnum;
  6458.     c[3] = (relocP->r_pcrel << 7) |
  6459.         (relocP->r_length << 5) | (relocP->r_extern << 4);
  6460. #endif
  6461.     ((u_char *) relocP)[4] = c[0];
  6462.     ((u_char *) relocP)[5] = c[1];
  6463.     ((u_char *) relocP)[6] = c[2];
  6464.     ((u_char *) relocP)[7] = c[3];
  6465.     }
  6466. #endif
  6467.     return;
  6468. }
  6469.  
  6470. static void
  6471. fix_symbol_root_byte_order(p)
  6472.     struct symbol_root *p;
  6473. {
  6474.  
  6475.     fix_byte_order(&p->format, sizeof(p->format));
  6476.     fix_byte_order(&p->length, sizeof(p->length));
  6477.     fix_byte_order(&p->ldsymoff, sizeof(p->ldsymoff));
  6478.     fix_byte_order(&p->textrel, sizeof(p->textrel));
  6479.     fix_byte_order(&p->datarel, sizeof(p->datarel));
  6480.     fix_byte_order(&p->bssrel, sizeof(p->bssrel));
  6481.     fix_byte_order(&p->filename, sizeof(p->filename));
  6482.     fix_byte_order(&p->filedir, sizeof(p->filedir));
  6483.     fix_byte_order(&p->blockvector, sizeof(p->blockvector));
  6484.     fix_byte_order(&p->typevector, sizeof(p->typevector));
  6485.     fix_byte_order(&p->language, sizeof(p->language));
  6486.     fix_byte_order(&p->version, sizeof(p->version));
  6487.     fix_byte_order(&p->compilation, sizeof(p->compilation));
  6488.     fix_byte_order(&p->databeg, sizeof(p->databeg));
  6489.     fix_byte_order(&p->bssbeg, sizeof(p->bssbeg));
  6490.     fix_byte_order(&p->sourcevector, sizeof(p->sourcevector));
  6491.     return;
  6492. }
  6493.  
  6494. #endif
  6495.  
  6496. #if defined(sun) && defined(sparc)
  6497. /*
  6498.  * The pagesize on the sun4 and the sparcStation are different.
  6499.  * We want to be able to run the binary on either, so we need to
  6500.  * use the larger of the two.  This is a hack to accomplish that.
  6501.  */
  6502. int
  6503. getpagesize ()
  6504. {
  6505.   return 8192;
  6506. }
  6507. #endif
  6508.  
  6509.